Drupal \Drupal\user\Entity\User how retrieve property - drupal

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....'

Related

Symfony API : test if the content has the keys

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.

Php error Notice:Undefined offset:255715

hello I'm working on a symfony2 project , and when I'm trying to create associative array this issue happend => Notice: Undefined offset :25715
My code editor alert me that the error come from when I'am create my assoiative array $Tableau_comptes_dependants
here is code
foreach ($tableau_compte_fictifs as $tableau_compte_fictif) {
$Tableau_id_compte_fictifs[] = $tableau_compte_fictif["id"];
}// this array content two value 25715 and 31170
foreach ($Tableau_id_compte_fictifs as $Tableau_id_compte_fictif) {
$Mes_comptes_reels_dependants = $mes_comptesRepo-
>all_client_compte_dependant($Tableau_id_compte_fictif);
if (count($Mes_comptes_reels_dependants) > 0) {
foreach ($Mes_comptes_reels_dependants as
$Mes_comptes_reels_dependant)
{
if (!in_array($Mes_comptes_reels_dependant,
$Tableau_comptes_dependants[$Tableau_id_compte_fictif]))
{
$Tableau_comptes_dependants[$Tableau_id_compte_fictif[] =
$Mes_comptes_reels_dependant;
}
}
}
}
return new JsonResponse(
array(
'code' => 200,
'result' => true,
'comptes' => $Tableau_id_compte_fictifs,
)
);
please let me know what I'am doing wrong
The notice is generated from your call to in_array:
if (!in_array($Mes_comptes_reels_dependant,
$Tableau_comptes_dependants[$Tableau_id_compte_fictif]))
You try to access your array on an index that does not exist, 25715, since this is the value of your variable which you pass between the square brackets.
You should check first, if an index exists with isset, before accessing it.
That said, I think your code has a design flaw if you run into problems like this. You should try to refactor it or talk with your co workers about how to simplify it. I must admit, that I, although I could, won't try solving this problem for you, since your variable names are basically unreadable.

Modifying a field collection programmatically missing hostEntity fields

I am trying to modify a field collection in a node that already exists so I can change an image on the first element in an array of 3. The problem is, the hostEntity info is not set when I do a entity_load or entity_load_single so when I do a:
$field_collection_item->save(true); // with or without the true
// OR
$fc_wrapper->save(true); // with or without the true
I get the following error:
Exception: Unable to save a field collection item without a valid reference to a host entity. in FieldCollectionItemEntity->save()
When i print_r the field collection entity the hostEntity:protected fields are indeed empty. My field collection is setup as follows:
field_home_experts
Expert Image <--- Want to change this data only and keep the rest below
field_expert_image
Image
Expert Name
field_expert_name
Text
Expert Title
field_expert_title
Text
Here is the code I am trying to use to modify the existing nodes field collection:
$node = getNode(1352); // Get the node I want to modify
// There can be up to 3 experts, and I want to modify the image of the first expert
$updateItem = $node->field_home_experts[LANGUAGE_NONE][0];
if ($updateItem) { // Updating
// Grab the field collection that currently exists in the 0 spot
$fc_item = reset(entity_load('field_collection_item', array($updateItem)));
// Wrap the field collection entity in the field API wrapper
$fc_wrapper = entity_metadata_wrapper('field_collection_item', $fc_item);
// Set the new image in place of the current
$fc_wrapper->field_expert_image->set((array)file_load(4316));
// Save the field collection
$fc_wrapper->save(true);
// Save the node with the new field collection (not sure this is needed)
node_save($node);
}
Any help would be greatly appreciated, I am still quite new to Drupal as a whole (end-user or developer)
Alright so I think I have figured this out, I wrote up a function that will set a field collection values:
// $node: (obj) node object returned from node_load()
// $collection: (string) can be found in drupal admin interface:
// structure > field collections > field name
// $fields: (array) see usage below
// $index: (int) the index to the element you wish to edit
function updateFieldCollection($node, $collection, $fields = Array(), $index = 0) {
if ($node && $collection && !empty($fields)) {
// Get the field collection ID
$eid = $node->{$collection}[LANGUAGE_NONE][$index]['value'];
// Load the field collection with the ID from above
$entity = entity_load_single('field_collection_item', array($eid));
// Wrap the loaded field collection which makes setting/getting much easier
$node_wrapper = entity_metadata_wrapper('field_collection_item', $entity);
// Loop through our fields and set the values
foreach ($fields as $field => $data) {
$node_wrapper->{$field}->set($data);
}
// Once we have added all the values we wish to change then we need to
// save. This will modify the node and does not require node_save() so
// at this point be sure it is all correct as this will save directly
// to a published node
$node_wrapper->save(true);
}
}
USAGE:
// id of the node you wish to modify
$node = node_load(123);
// Call our function with the node to modify, the field collection machine name
// and an array setup as collection_field_name => value_you_want_to_set
// collection_field_name can be found in the admin interface:
// structure > field collections > manage fields
updateFieldCollection(
$node,
'field_home_experts',
array (
'field_expert_image' => (array)file_load(582), // Loads up an existing image
'field_expert_name' => 'Some Guy',
'field_expert_title' => 'Some Title',
)
);
Hope this helps someone else as I spent a whole day trying to get this to work (hopefully I won't be a noob forever in Drupal7). There may be an issue getting formatted text to set() properly but I am not sure what that is at this time, so just keep that in mind (if you have a field that has a format of filtered_html for example, not sure that will set correctly without doing something else).
Good luck!
Jake
I was still getting the error, mentioned in the question, after using the above function.
This is what worked for me:
function updateFieldCollection($node, $collection, $fields = Array(), $index = 0) {
$eid = $node->{$collection}[LANGUAGE_NONE][$index]['value'];
$fc_item = entity_load('field_collection_item', array($eid));
foreach ($fields as $field => $data) {
$fc_item[$eid]->{$field}[LANGUAGE_NONE][0]['value'] = $data;
}
$fc_item[$eid]->save(TRUE);
}
I hope this helps someone as it took me quite some time to get this working.

Adding an array of an array at Amazon DynamoDB

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

Create node programmatically with cck location field

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

Resources