Change fields in node from code - drupal

How do I access the fields in a node in Drupal 7.
I have tried this but that do not work.
$node=node_load($nid);
$node->field_num[LANGUAGE_NONE][0]['value']=$num;
I think I have to be more specific:
I first create a node and set values on some fields like this:
$values = array(
'type' => 'scorings',
'uid' => $user->uid,
'status' => 1,
'comment' => 0,
'promote' => 0,
);
$entity = entity_create('node', $values);
$ewrapper = entity_metadata_wrapper('node', $entity);
$entity->field_rond_nid[LANGUAGE_NONE][0]['value']=$nid_scorekort;
$entity->field_golfid[LANGUAGE_NONE][0]['value']=$form_state['values']['golfid_1'];
$ewrapper->save(true);
entity_save('node', $entity);
$nid=$entity->nid;
This works fine. Then I want to access this node from another function (passing the nid to it) end set value to another field (field_score_1). I have tried this:
$node=node_load($nid, 'my_content type');
$node->field_score_1[LANGUAGE_NONE][]['value'] = $my_value;
But this do not work. Seams that node_load do not give me access to the fields.

Your node_load() call is incorrect.
From the Drupal API documentation for node_load() the function declaration is:
node.module node_load($nid = NULL, $vid = NULL, $reset = FALSE)
Your second parameter is a string, not a number, as $vid would be.
If node_load() returns a FALSE then it failed.
Perhaps you were wanting to use EntityFieldQuery() instead?

Related

How to create Field Collection Item by code in Drupal 8

How to create a Field Collection item for a node by program in Drupal 8. I have tried with below code, but it doesn't work. 'field_abc_inside' is the field of the Field Collection 'field_abc'.
$field_collection_item = entity_create('field_collection_item', array(
'field_name' => 'field_abc',
'field_abc_inside' => array('value'=> 'Test data'),
));
$field_collection_item->setHostEntity($node);
$field_collection_item->save();
$user_id = \Drupal::currentUser()->getAccount()->id();
$user = User::load($user_id);
$fc = FieldCollectionItem::create(array(
"field_name" => "field_hobbies",
));
$fc->set('field_hobby_name', 'Watch TV');
$fc->setHostEntity($user);
That code helped me but I have one observation.
\Drupal::currentUser() is the user object, which is clear since it is using it to retrieve the id().
Therefore no need to User::load() it again in line 2, redundant processing that will cause the function to take longer to run.
// Get the current user object
$user = \Drupal::currentUser();
// Prepare the new Field Collection Item object
$fc = FieldCollectionItem::create(array(
"field_name" => "field_hobbies",
));
// Sets more field values
$fc->set('field_hobby_name', 'Watch TV');
// Sets the host record; where the field collection will be attached into
$fc->setHostEntity($user);
// Saves it into an actual field collection record
$fc->save();

A reference to the object element Symfony2

I try to get to "content" from message entity.
This is my dump($messages):
http://s13.postimg.org/96ytd93vb/message.png
and my code in controller:
$em = $this->getDoctrine()->getEntityManager();
$messages = $em->getRepository('DashboardMainBundle:Message')->findBy(
array(
'receiver'=> $UserId,
'id' => $Id
),
array('createdAt' => 'ASC')
);
How can I take "content" from this array in controller?
It looks simple but I tried many methods but each failed...
For what you've currently shown, you got an array result. Currently your Message instance is being stored in $messages[0]. So you either have to iterate over your result (if you expect more than one record) or replace your findBy with findOneBy if you expect one record.

Creating a Pods relationship programmatically produces error in Advanced Custom Fields

I'm trying to create a pods relationship using the following code:
$data = array(
"pod_id" => esc_attr(strip_tags($_POST['customMetaAutorID'])),
"field_id" => 1073,
"item_id" => $post_id,
"related_item_id" => $_POST["customMetaAutorID"],
"related_pod_id" => 0,
"related_field_id" => 0,
"weight" => 0
);
$wpdb->insert("wp_podsrel", $data);
The row gets added to the table, how ever, after a few page refreshes I start getting the error:
Strict Standards: Declaration of acf_taxonomy_field_walker::start_el() should be compatible with Walker::start_el(&$output, $object, $depth = 0, $args = Array, $current_object_id = 0)
This means that all I have is the white screen of death and the only thing I can do is to restore the database.
What's the way to add a pods relationship field value and not breaking everything else?
Found out the answer myself.
Turns out each pod item has an add_to function wich adds values to related fields given the field name (much more convenient than harcoding the field ID)
The code I ended up using is this:
$postPod->add_to("field_name", $related_element_id);

how to populate text area with database value before form load in drupal 7?

I have used hook_form_FORM_ID_alter( ) function to alter a menu_edit_menu form to add few fields. I ve stored the values from those fields in a table when submit action is performed. what I need now is when the particular form entry is loaded again for editing. The fields should be populated with the data in the database before form loads. Can anyone tell me how this could be done.
I have tried using hook_validate ( ) function but the function is called when the submit action is performed which is of no use in this regard. I have to perform the database query before the form gets rendered to populate the text fields with data from tables. Kindly provide me some insight into how this could be accomplished.
I have a problem with the sql select query as well/
$query = db_select('menu_custom');
$query
->fields(array('menu_name','role1','role2','role3'))
->condition('check',1,'=')
->conditon('title',$form_state['values']['title'])
->execute();
foreach($query as $record)
{
$mname = $result ->menu_name;
$rl1 = $result -> role1;
$rl2 = $result -> role2;
$rl3 = $result -> role3;
dpm($mname." ".$rl1);
}
I am getting error that my field specification is wrong but I cant figure out the problem there.
This is a bit too long for a comment so I'll put it here:
The only error you've got in your query is that the first argument passed to the fields() function needs to be the name/alias of the table from which the fields are coming. So your query should probably look something like this:
$query = db_select('menu_custom')
->fields('menu_custom', array('menu_name','role1','role2','role3'))
->condition('check',1,'=')
->conditon('title',$form_state['values']['title'])
->execute();
You get the data from your database in your form function, and put them as default_value
$name = db_query(YOUR_SQL);
$form['first_name'] = array(
'#title' => t('First Name'),
'#type' => 'textfield',
'#default_value' => $name,
);
is this what you meant?

calling user_save from within hook_init failing on Drupal6

I have a module that implements hook_init.
Within that I have a case where I try to call user_save like save
user_save ('');
I figure this should work since I am not setting a uid, so it should create a new one. It also says that the $array should be allowed to be empty.
However, this always returns FALSE. ??
I have also tried setting these values in $array but this doesn't work either:
$foo = array(
'name' => 'the new user',
'mail' => 'the new user mail',
'pass' => user_password(),
'status' => 1,
);
$new_user = user_save ('', $foo);
Look at the documentation:
Parameters
$account The $user object for the user to modify or add. If $user->uid is omitted, a new user will be added.
$array (optional) An array of fields and values to save. For example, array('name' => 'My name'); Setting a field to NULL deletes it from the data column.
So when you call user_save() the first parameter must be a user object. If that user object doesn't have a uid, or is a string like in your case, a new user will be created. Here the 2nd parameter is necessary. It's not required to use the function, but as it holds all the values you want to save, you wont get far trying to create a user with no data at all. What use is a user without password, username etc. So a minimum of data is required as well, so Drupal will know what to save.

Resources