I know that AmazonDB supports number, string, number set and string set as item types. But, how about a set of an string set (array of array, or multidimensional array)?
In case it's possible, this is the only way I found to do that, which didn't work (using PHP):
$units_frequencies["id"][0] = "400";
$units_frequencies["id"][1] = "401";
$units_frequencies["id"][2] = "402";
$units_frequencies["frequency"][0] = "20";
$units_frequencies["frequency"][1] = "30";
$units_frequencies["frequency"][2] = "50";
// item that will be inserted
$item = array(
'id' => array(AmazonDynamoDB::TYPE_STRING => $id),
'arrays_field' => array(
AmazonDynamoDB::TYPE_ARRAY_OF_STRINGS => array(
AmazonDynamoDB::TYPE_ARRAY_OF_STRINGS => $units_frequencies)));
I don't want to have two columns (one for $units_frequencies["id"] and $units_frequencies["frequency"]) because the second one can have two index with the same values, which is not allowed by Dynamo.
Thanks in advance.
It doesn't.
At least while looking at AttributeValue.class (AWS Java SDK)
I also couldn't find any hint on the documentation site except for those dealing with int, string, set of string or set of int
You can eventually serialize your object. More info at https://java.awsblog.com/post/Tx1K7U34AOZBLJ2/Using-Custom-Marshallers-to-Store-Complex-Objects-in-Amazon-DynamoDB
Related
i come from ES6 and need to do something in one Drupal 8 site.
Basically I try to get some value from the current logged user object.
...i try any possible method but nothing good.
by this snippet of code i can dump($userx) variable, i need to parse
$userCurrent = \Drupal::currentUser();
$uid = $userCurrent->id();
$userx = \Drupal::entityTypeManager()->getStorage('user')->loadByProperties([
'uid' => '13465'
]);
dump($userx);
outpup see picture
$cf = $userx->get('field_codice_fiscale_user')->getvalue()[0]['value'];
dump($cf);
otput NULL
Results output
i need the value of
protected values
field_cv_codice_fiscale
x-default => array (1)
0 => array (1)
value => string (16) "DSSSLV83D67B35QV"
i tried:
$cf = $userx->get('field_codice_fiscale_user')->getvalue()[0]['value'];
again NULL
my goal is to have variable valorized by :
'field_codice_fiscale_user' -> value;
after struglling two days i need to give up to drupal folly.
Thank you in advance
I found the solution.
as reported in the Drupal specification, entityTypeManager return objects array.
so the corect snippet is:
$userx = \Drupal::entityTypeManager()->getStorage('user')->loadByProperties([
'uid' => $uid2 ]);
dpm($userx);
$cfx = $userx[$uid2];
now the variable $cfx contain objects (inpictures = '3465' objects).
we can access the object property by this way
if(isset($cfx->get('field_codice_fiscale_user')->getvalue()[0]['value'])) {
$cf = $cfx->get('field_codice_fiscale_user')->getvalue()[0]['value'];
} else { $cf = '';}
dmp($cf)
output
$scf = 'DSLL....'
With Symfony, I can get the content of request (POST and application/json) with :
$content = json_decode($request->getContent());
dd($content) return :
[
"subject" => "test"
"content" => "content"
]
I just want to hydrate an object with the subject, this works good :
$subject = new SubjectEntity();
$subject->setSubject($content['subject]);
But I don't want to do a setSubject() if the subject key doesn't exist.
I know I can do an if for each variable (Or $subject->setSubject($content['subject] ?? null)), but I think it will be a bit tedious in more complex cases.
Is there a way to "validate" the content sent to verify that all the desired keys are present ?
The cleanest solution would be a request param validator using symfony validator
Example:
public function validateRequest(array $params): array
{
$validator = Validation::createValidator();
$constraints = new Assert\Collection([
'subject' => new Assert\Type('string'),
'content' => new Assert\Type('string'),
]);
$group = new Assert\GroupSequence(['Default', 'custom']);
return $validator->validate($params, $constraints, );
}
If the keys can be optional, then you must use Assert\Optional(). Either way, you will need the null coalescing operator to cast to null if the key isn't set.
You can put these in a different class and with a small refactor you can make it work much nicer than doing a bunch of ifs, and it can be re-used to validate all of your api requests.
I have an entity that has multiple keys, how would I go about finding the proper object based on multiple ids?
$product = $em->getRepository('AcmeStoreBundle:Product')->find($id);
It's a little confusing what you're asking here. It sounds as though you have an entity with a compound key (primary key relates to multiple columns) and want to find it based on it's primary key values, yes?
If so, the find method will require an array containing values for each of the fields that make up the key:
$product = $em->getRepository('AcmeStoreBundle:Product')->find(array(
'key1' => 'value1',
'key2' => 'value2'
));
Alternatively, you could use findOneBy method. This would be useful for when the combination of the provided fields are not unique as you're able to provide a second argument to define the ordering.
$product = $em->getRepository('AcmeStoreBundle:Product')->findOneBy(array(
'key1' => 'value1',
'key2' => 'value2'
), array('updated_at' => 'DESC'));
See http://symfony.com/doc/2.0/book/doctrine.html#fetching-objects-from-the-database
$product = $em->getRepository('AcmeStoreBundle:Product')->findBy(
array('key1' => 'value1', 'key2'=>'value2')
);
I'm writing a wrapper class for my drupal 7 site which lets me connect to and query my phpbb database.
When connecting to an external data source (as per drupal documentation) you have set the active db, run the query, then set the active db back to the default.
e.g.
db_set_active('phpbb');
$result = db_query($sql,$args,$opts);
db_set_active();//back to default
But is there any way to use drupal's database wrapper to create a brand new connection which can be permanently set to the new database without having to do this switching back-and-forth nonsense? surely we can handle connections to multiple databases concurrently.
I have done some googling but haven't found anybody trying to do this as yet.
Typical. 5 minutes after posting i figure it out... so, for future googlers:
Basically, you don't use db_query, instead you run the query on your connection without setting the active link.
you can figure this out by looking at how db_query works:
http://api.drupal.org/api/drupal/includes--database--database.inc/function/db_query/7
So it looks like this:
$target='default';
$key = 'phpbb';
$phpbb = Database::getConnection($target,$key);
$result = $phpbb->query($sql,$args,$opts);
This assumes you have a database configured in your settings.php like the following:
$databases['phpbb']['default'] = array(
'driver' => 'mysql',
'database' => 'forum',
'username' => 'username',
'password' => 'password',
'host' => 'mysql.host.com',
'prefix' => 'phpbb3_'
);
Database::addConnectionInfo() perhaps?
This method allows the addition of new connection credentials at
runtime. Under normal circumstances the preferred way to specify
database credentials is via settings.php. However, this method allows
them to be added at arbitrary times, such as during unit tests, when
connecting to admin-defined third party databases, etc.
If the given key/target pair already exists, this method will be
ignored.
The definition for getConnection cites a different order for arguments than used above.
function getConnection($target = 'default', $key = NULL)
This is sadly different from Database::addConnectionInfo() which is
public static function addConnectionInfo($key, $target, $info)
Also, on DB_select, the $key is not a parameter, though it is in the options array:
function db_select($table, $alias = NULL, array $options = array()) {
if (empty($options['target'])) {
$options['target'] = 'default';
}
return Database::getConnection($options['target'])->select($table, $alias, $options);
}
while
final public static function getConnection($target = 'default', $key = NULL) {
so this implies that the 'master' or 'slave' or 'default' is always used as set, but not the key to the alternative database/schema, requiring the db_set_active('...'); and db_set_active(); around the db_select.
Since calls to other dbs can easily be required within the processing of the db_select (such as devel calls or calls in alters), this is inflexible design. Changing this call:
return Database::getConnection($options['target'])->select($table, $alias, $options);
to add the Key parameter (it is already spec'd as an argument!!) is needed but insufficient so far as I can now see.
I try to programmatically create a node of custom contenttype "location" in Drupal 6, with the node containing a location field (http://drupal.org/project/location) called "location" (yes I know, the nomenclature could be better, but I am just experimenting on this at the moment).
Creating the node works just fine, but I cannot find a way to set the contents for the location field - i.e. the node is created with all content but the value for then location field.
I try creating the node like this:
$newNode = (object) NULL;
$newNode->type = 'location';
$newNode->title = $locationName;
$newNode->uid = $userId;
$newNode->created = strtotime("now");
$newNode->changed = strtotime("now");
$newNode->status = 1;
$newNode->comment = 0;
$newNode->promote = 0;
$newNode->moderate = 0;
$newNode->sticky = 0;
$newNode->field_location[0]['street'] = 'Teststraße';
$newNode->field_location[0]['postal_code'] = '12345';
$newNode->field_location[0]['city'] = 'Musterstadt';
node_save($newNode);
The node gets created with the correct title, but the location fields remain unset.
How can I programmatically set the location-related fields?
Thanks in advance!
Wanted to add this as a comment, but it seems like putting code into the comment is rather problematic. So here we go: I changed the internas so that I do not use a cck field anymore, but use the default location option as suggested by googletorp.
The actual code to create a new location and assign this to a new node looks like this:
$location['street'] = "myStreet";
$location['postal_code'] = "12345";
...
$newLocationId = location_save($location);
$newNode = ...
$newNode->locations[0]['lid'] = $newLocationId;
node_save($newNode);
Thanks for the guidance :)
Instead of node_save, many people recommend using drupal_execute to programmatically submit the node edit form. This gives you the benefit of form validation.
See http://thedrupalblog.com/programmatically-create-any-node-type-using-drupal-execute for an excellent example of using drupal_execute. Don't forget to look at the comment http://thedrupalblog.com/programmatically-create-any-node-type-using-drupal-execute#comment-70 to see some additional info on CCK fields.
The advantage of drupal_execute is that you get form validation also. So after the drupal_executestatement you can see if there were any errors using form_get_errors ( http://api.drupal.org/api/function/form_get_errors/6 ). See snippet (pasted below) from http://civicactions.com/blog/cck_import_and_update for an example of using form_get_errors
$node->type = 'yourtype';
$values = array();
$values[...] = ...;
drupal_execute('yourtype_node_form', $values, $node);
$errors = form_get_errors();
if (count($errors)) {
// do something ...
}
Another very nice resource on programmatic submission of nodes using drupal_execute can be found at http://drupal.org/node/293663
I have done this, only not with a CCK field but the default location option you can add to nodes.
What I did to make it work, was to first save the location (there's an API function for it) and then add the location id from the saved location.
Sample code:
Note, $center is from an external source, so it's not Drupal related. I know all my locations are from Denmark in my example, so that part is just hardcoded.
When you don't use a CCK field, you don't need to save the location data on the node, instead you can just save the location and pair the location yourself. It's a quick solution, instead of running through the node form like suggested. For complex nodes, that might be the better choice, but when it's simple, this is done faster.
// Update the location data.
$location = is_array($node->location) ? $node->location : array();
$location += array(
'street' => $center->address->address2,
'city' => $center->address->zipName,
'postal_code' => $center->address->zip,
'country' => 'dk',
'country_name' => 'Denmark',
);
location_save($location);
// Insert location instance, if it's not set yet.
$criteria = array(
':nid' => $node->nid,
':vid' => $node->vid,
':lid' => $location['lid'],
);
if (!db_result(db_query("SELECT COUNT(*) FROM {location_instance} WHERE nid = %d AND vid = %d AND lid = %d;", $criteria))) {
db_query("INSERT INTO {location_instance} (nid, vid, lid) VALUES (%d, %d, %d)", $criteria);
}
For Drupal 7, saving as default location tab.
$location = array(
'latitude' => $row->gmapycord,
'longitude' => $row->gmapxcord,
);
$lid = location_save($location);
if ($lid) {
$entity->locations['0']['lid'] = $lid;
}
Inspired from: here