I currently have this statment:
$query = 'SELECT DataStream__c from JUS_Contract__c limit 50';
Which works fine, but I want to only select the datastream when Datavalue = 3;
for example:
$query = 'SELECT DataStream__c from JUS_Contract__c where DataValue__c=3 limit 50';
When this is atempted I get a notice saying:
Trying to get property of non-object
I know this is because DataValue returns something like this:
stdClass Object ( [Id] => [DataValue__c] => 3)
When I do:
$query = 'SELECT DataStream__c from JUS_Contract__c limit 50';
$response = $mySforceConnection->query(($query));
//print_r($response->records);
foreach ($response->records as $record) {
print_r($record);
(for printing I fixed it by doing this: echo $record->DataStream__c; )
However I can not do that in the query, and am unsure how to change it to either a string or a int inside the query so that I can use the where command on it. Any suggestions would be great.
Related
I have a client who is wanting the product search in the admin area to ignore the fact that there are special characters in the product names.
For example, they have a lot of products listed with the word “kings” or the word “king’s” with an apostrophe - both used correctly grammatically depending on the product.
What they want to be able to do is search for “kings” on the admin area and all products called “kings” and “king’s” appear - rather than just “kings” as it does by default.
They have the same problem with “remy” and “r.e.m.y” where, when searching for “remy” the search needs to ignore the fact that there are “.” In the name.
Opencart Version 2.3.0.2
Any help is greatly appreciated!
Look, if you have expirience you can do it easily, just find search query in Opencart and replace all special symbols with empty string, check this example if you have r.e.m.y in your database table blog, title column with value 'r.e.m.y, then this query will return you record
SELECT * FROM `blog` WHERE title = replace(title,'.','') = 'remy'
Check image for example:
Example is for points '.' only but you can do replace and for other special symbols.
Let me show you where to find this query:
First you can see link is catalog/product, so your controller is
in admin/catalog/product, when u type something in "title" input, it send GET parameter &filter_name to this controller. You can check the controller for that filter, see:
protected function getList() {
if (isset($this->request->get['filter_name'])) {
$filter_name = $this->request->get['filter_name'];
} else {
$filter_name = null;
}
Here it check for this GET parameter and set it to variable $filter_name, then bellow the code it send this variable to model:
$filter_data = array(
'filter_name' => $filter_name,
'filter_model' => $filter_model,
'filter_price' => $filter_price,
'filter_quantity' => $filter_quantity,
'filter_status' => $filter_status,
'filter_image' => $filter_image,
'sort' => $sort,
'order' => $order,
'start' => ($page - 1) * $this->config->get('config_limit_admin'),
'limit' => $this->config->get('config_limit_admin')
);
$product_total = $this->model_catalog_product->getTotalProducts($filter_data);
It set array with variables then u call $this->model->catalog->product->getTotalProducts, so there is query u need:
public function getTotalProducts($data = array()) {
$sql = "SELECT COUNT(DISTINCT p.product_id) AS total FROM " . DB_PREFIX . "product p LEFT JOIN " . DB_PREFIX . "product_description pd ON (p.product_id = pd.product_id)";
$sql .= " WHERE pd.language_id = '" . (int)$this->config->get('config_language_id') . "'";
if (!empty($data['filter_name'])) {
$sql .= " AND pd.name LIKE '" . $this->db->escape($data['filter_name']) . "%'";
}
if (!empty($data['filter_model'])) {
$sql .= " AND p.model LIKE '" . $this->db->escape($data['filter_model']) . "%'";
}
if (isset($data['filter_price']) && !is_null($data['filter_price'])) {
$sql .= " AND p.price LIKE '" . $this->db->escape($data['filter_price']) . "%'";
}
if (isset($data['filter_quantity']) && !is_null($data['filter_quantity'])) {
$sql .= " AND p.quantity = '" . (int)$data['filter_quantity'] . "'";
}
if (isset($data['filter_status']) && !is_null($data['filter_status'])) {
$sql .= " AND p.status = '" . (int)$data['filter_status'] . "'";
}
if (isset($data['filter_image']) && !is_null($data['filter_image'])) {
if ($data['filter_image'] == 1) {
$sql .= " AND (p.image IS NOT NULL AND p.image <> '' AND p.image <> 'no_image.png')";
} else {
$sql .= " AND (p.image IS NULL OR p.image = '' OR p.image = 'no_image.png')";
}
}
$query = $this->db->query($sql);
return $query->row['total'];
}
If you don't have expirience with Opencart it will be not so easy, but it's possible.
One hint: u can use your own query if this parameter is set (if-else) :)
I am writing a spark job which iterates through dataset and finds matches, here's what the pseudo code looks like:
def map(data: Dataset[Row], queries: Array[Row]): Dataset[Row] = {
import spark.implicits._
val val1 = data
.flatMap(r => {
val text = r.getAs[String]("text");
queries.filter(t => t.getAs[String]("query").r.findFirstIn(message).text)
.map(..//mapping)
}).toDF(..columns);
}
So, it iterates through the data and performs regex matching. The issue is, it tries to convert string into regex (t.getAs[String]("query").r) every time, and I am trying to swap it outside the loop as it's not really needed.
So, I tried this (where queries array is generated):
val convertToRegex = udf[Regex, String]((arg:String) => if(arg != null) arg.r else null)
queries.withColumn("queryR", convertToRegex(col("query"))) //queries is DataFrame here
However, as expected, it threw an error saying (Schema for type scala.util.matching.Regex is not supported).
Is there any way I can add a Regex column into an array or create a temp column before stating the iteration?
Drupal\node\Entity\Node Object
(
[in_preview] =>
[values:protected] => Array
(
[vid] => Array
(
[x-default] => 1
)
[langcode] => Array
(
[x-default] => en
)
[field_destination] => Array
(
[x-default] => Array
(
[0] => Array
(
[target_id] => 2
)
)
)
Not able to get field_destination value directly. It's a taxonomy term attached with the content type. Any help appriciated.
To build on VJamie's answer.
You will need to either set a use statement at the top of your script;
use Drupal\taxonomy\Entity\Term;
Or, prefix the class instance with the namespace;
$term = \Drupal\taxonomy\Entity\Term::load($node->get('field_destination')->target_id);
That will get rid of the fatals.
You can also use some methods from EntityReferenceFieldItemList:
Gets the entities referenced by this field, preserving field item deltas:
$node->get('field_destination')->referencedEntities();
Hope it will be useful for you
The following code will get you the term object you need.
$term = Term::load($node->get('field_destination')->target_id);
If you need the name of that term you can do the following
$name = $term->getName();
Hope this helps out!
Do this
use Drupal\taxonomy\Entity\Term;
$term = Term::load($node->get('field_destination')->target_id);
$termname = $term->getName();
In drupal8 we used to follow oops approach to get the values.
This is the correct way on how to achieve it
use Drupal\taxonomy\Entity\Term;
function modulename_node_presave(Drupal\Core\Entity\EntityInterface $entity) {
switch ($entity->bundle()) {
case 'programs':
$term = Term::load($entity->get('field_program_names')->target_id);
$name = $term->getName();
$entity->setTitle($name);
break;
}
}
entity property can be accessed directly from any reference type field.
$node = 'myNode';
$termEntity = $node->get('field_taxonomy_reference')->entity;
if ($termEntity instanceof TermInterface) {
$termLabel = $termEntity->label();
}
Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 8 years ago.
Improve this question
If I have a hash that "describes" attributes of objects i.e. names and types like:
{
column_defs => {
serial_id => { type => INTEGER },
first_name => { type => CHAR(40) },
salary => { type => DOUBLE },
},
}
The actual hash might be changed but I don't think that the definition affects my core question.
What is a good way to check if the types of each field is defined correctly? E.g. that salary is not defined FLOAT or serial_id is not string etc. (but what should or should not be should be configurable)
I am not sure what would be the best way to define these actual "restrictions" and how to apply them on the hash.
It sounds like you just want to do string comparison between values in a file and values in a hash:
use strict;
use warnings;
use 5.010;
my %column_defs = (
serial_id => { type => 'INTEGER' },
first_name => { type => 'CHAR(40)' },
salary => { type => 'DOUBLE' },
);
while (<DATA>) {
my ($column, $type) = split;
if (my $def = $column_defs{$column}) {
say "'$column' should be $def->{type} but is $type" if $def->{type} ne $type;
}
}
__DATA__
salary DOUBLE
serial_id FLOAT
first_name CHAR(20)
foo BAR
Note that for simplicity, I made the column definitions from your snippet into their own hash.
Output:
'serial_id' should be INTEGER but is FLOAT
'first_name' should be CHAR(40) but is CHAR(20)
EDIT: Misread the question, or rather, didn't see the relevant comment until it was too late - doh! This answer is for checking the values of the fields conform to the specs. Maybe you'll want to do that later! ;-)
You can do this kind of checking manually by setting up tests for the different types of data you're looking at and then running them on the data, e.g.
## tests
sub integer {
return 1 if $_[0] =~ /^[0-9]+$/;
return 0;
}
sub string {
return 1 if $_[0] =~ /^[\w\s]+$/;
return 0;
}
sub char_40_ {
return 1 if length($_[0]) <= 40;
return 0;
}
sub double {
(etc.)
...
# set up a dispatch hash
my %d_hash = (
serial_id => \&integer,
first_name => \&char_40_,
salary => \&double,
another_field => \&integer,
more_data => \&string,
);
Then you can check that the data in the fields matches the specs by calling the appropriate sub:
$d_hash{ $field_name }->( $value_of_field )
Depending on how many different types of data you're looking at, and the number of each, you may want to set up specific tests, e.g. CHAR(40) runs a specific test for fields of 40 chars or less, or you could parse the type field and apply a test for CHARs and for length 40 or less.
I must admit I'm not 100% clear what you're asking, but perhaps something like this might be helpful...?
use strict;
use warnings;
use Types::Standard qw( Dict );
use Types::XSD::Lite qw( String Integer Float );
my $check = Dict[
serial_id => Integer,
first_name => String[ maxLength => 40 ],
salary => Float,
];
$check->assert_valid({
serial_id => 999,
first_name => "Alice",
salary => 20_000.00,
});
$check->assert_valid({
serial_id => 999,
first_name => "Bob",
salary => "peanuts", # fails
});
Not 100% clear what you're asking...
When you define an object, you're suppose to use your methods to verify an object. Here's a very simple example:
package Local::Employee;
use strict;
use warnings;
use Carp;
use Scalar::Util qw(looks_like_number);
use feature qw(say state);
sub new {
my $class = shift;
my $first_name = shift;
my $salary = shift;
my $self = {};
bless $self, $class;
$self->serial;
$self->first_name( $first_name );
$self->salary( $salary );
return $self;
}
sub serial {
my $self = shift;
my $bad_boy = shift;
state $serial = 0;
if ( defined $bad_boy ) {
croak( qq(Cannot set serial number. You can only retrieve it.) );
}
if ( not exists $self->{SERIAL} ) {
$self->{SERIAL} = sprintf "%04d", ++$serial;
}
return $self->{SERIAL};
}
sub first_name {
my $self = shift;
my $first_name = shift;
if ( defined $first_name ) {
if ( length $first_name > 40 ) {
croak( qq(First name can't be longer than forty characters.) );
}
$self->{FIRST_NAME} = $first_name;
}
return $self->{FIRST_NAME};
}
sub salary {
my $self = shift;
my $salary = shift;
if ( defined $salary ) {
if ( not looks_like_number $salary ) {
croak( qq(Salary must be numeric) );
}
$self->{SALARY} = $salary;
}
return $self->{SALARY};
}
sub employee {
my $self = shift;
my %employee_hash = %{ $self };
return \%employee_hash;
}
1;
Notice that each of my methods verify their data. Also notice that my new constructor doesn't know how the data itself is stored. It merely calls the methods for each piece of data. You can bless an object and use the various methods before you return the object to the main program.
Also notice that if I return the whole structure, I dereference my hash reference, and then return that hash reference. In other words, when I return my structure, you get a copy of that structure and not the structure itself. Futzing with $employee->{NAME} isn't going to change the actual name of the object.
Is this totally protected? No. A bad player could use Data::Dumper, get the structure of my object, and then set $self->{NAME} = $name instead of calling $self->name($name). There is a concept of Inside-Out Objects, but most developers have agreed it's more trouble than it's worth. Makes debugging really difficult.
Maybe what you want is more flexibility, you want to define an object's structure on the fly, and verify it.
Take a close look at all of my methods, and you can see they're all very similar in how they work. I could almost create a template. In fact, there are template classes like Class::Struct that allow you to create classes on the fly. Class::Struct defines subroutines that act as methods based upon your field names and puts those subroutines in a namespace you've defined as you class. If you have a class called Foo with a method bar, a subroutine called Foo::bar will be defined, and of course it will also create a subroutine Foo::new to use as a constructor. Once you've defined a class, you can use it just like a normal class:
my $foo = Foo->new(-bar => "bar value");
say "The value of bar is: " . $foo->bar";
If I were you, I wouldn't bother to create real classes because it's rather complex. Instead, I would have a class that allows me to create other classes.
Autoloading is a way of defining a single subroutine called AUTOLOAD that allows you to implement multiple methods without you having to define each and every one. When you call a method like this:
$employee->first_name("Bob");
Perl looks through your subroutines for one named first_name. If it can't find one, it looks for one called AUTOLOAD and sends it the parameters and sets $AUTOLOAD to the name of the method being called.
Let's say you have a hash of classes that contains two classes, one employee and one car:
$VAR = {
"employee" => "FIELDS" => {
"first_name" => "string:40",
"serial" => "serial:d09",
"salary" => "float:%8.2f",
}
{
"cars" => "FIELDS" => {
"license" => "string:9",
"make" => "string:20",
"model" => "string:20",
"top_speed" => "integer:4",
}
}
Now imagine a way to create a new class like this:
my $employee = Local::Class->new( "employee", {
-first_name => "Bob",
-salary => 342.95,
},
);
my $car = Local::Class->new( "car", {
-make => "Chevy",
-model => "Lumina",
-engine => "1.2",
},
);
You could use your new constructor subroutine to set all of those fields via the AUTOLOAD subroutine. Once done, you can treat each object as a class. Let's say you want to know the name of the employee:
say "The employee's name is " . $employee->name;
This could be handled by an AUTOLOAD subroutine that sees what type of class employee is, then verifies if name is even a valid method. If it is, it returns the value of that hash key. Let's take a look at setting:
$employee->name("Bob, the one and true King of France. All hale his majesty");
It again uses AUTOLOAD to verify that name is a valid field, and that the value you're setting is a valid name. (In this case, the subroutine will croak with a name too long error).
Is that more what you want to do? You'll have to have a way of creating your class hash, and making sure that it cannot be changed once set. Then, you simply have to be able to use that hash to verify each object you're creating.
Here is my code:
var qryStr = "
UPDATE templates_email
SET title = :title, test_emails = :testEmail, body = :body
WHERE id = :templateID";
q = New Query();
q.setSQL(qryStr);
q.addParam(name="title", value="#arguments.title#", cfsqltype="cf_sql_char");
q.addParam(name="body", value="#arguments.templateContent#", cfsqltype="cf_sql_char");
q.addParam(name="testEmail", value="#arguments.test_emails#", cfsqltype="cf_sql_char");
q.addParam(name="templateID", value="#arguments.id#", cfsqltype="cf_sql_integer");
return q.execute().getResult();
This is the error:
Parameter 'body WHERE' not found in the list of parameters specified
SQL: UPDATE templates_email SET title = :title, test_emails = :testEmail, body = :body WHERE id = :templateID
The error occurred in C:\ColdFusion9\CustomTags\com\adobe\coldfusion\query.cfc: line 108
I can only assume I have done something wrong with the way my SQL is structured with the parameters, but can't work out what it is. Can anyone see what I am doing wrong here?
The parser for getting the params doesn't tokenize on return values, only on whitespace (which is really annoying). Try the following:
var qryStr = "
UPDATE templates_email
SET title = ( :title ), test_emails = ( :testEmail ), body = ( :body )
WHERE ( id = :templateID )
";
The ( and ) should remove any issue with where the parser not being able to recognise where the :params stop and start.
This error occurs because of the tab and line break characters found in your SQL statement. I normally run below function on my SQL statement to remove these characters.
string function cleanSQL(required string sqlStatement)
output="false"
{
return trim(reReplace(arguments.sqlStatement, "\t|\n", " ", "all"));
}
So, your setSQL() can look like:
q.setSQL(cleanSQL(qryStr))
or simply:
q.setSQL(reReplace(qryStr, "\t|\n", " ", "all"))
ColdFusion can get confused when parsing the SQL string to use parameters. The easiest way to solve this shortcoming is to put a space after each of your parameters.
Since some text editors may remove trailing whitespace, like when saving, I include an empty comment after any space at the end of a line.
var qryStr = "
UPDATE templates_email
SET title = :title , test_emails = :testEmail , body = :body /**/
WHERE id = :templateID /**/
";