I have a custom module that implements hook_node_presave(). I have a field collection item(field_alternative_titles) attached to one of my content types(disease topic), I have a link field (field_alternative_titles_title) that is attached to my field collection item(field_alternative_titles). When I add a node of the disease topic content type, in my custom module I want to grab it's url and title, and populate the field_alternative_titles_title field. I have tried several things, but I haven't been able to figure out how to do that. How can I populate that field in a custom module?

Comments

Stefan Lehmann’s picture

How I would do it.

  • Install Devel module and goto a node with a properly filled out field.
  • Click the Devel tab at the top of the node edit form to see the whole node object.
  • Click your way through to the field collection in the debug representation of the $node object.
  • Add your custom value(s) in hook_node_presave to the $node object according to the data structure in your example node in the Devel tab.

Good luck.

I like cookies!

Eluchel’s picture

so doing something like:

$node->field_alternative_titles[$node->language][0]['field_alternative_titles_title'][$node->language][0]['
title'] = $node->title;

Would that work? Would hook_node_presave fill in the rest of the data to create the instance of the field_alternative_titles_title field?

Stefan Lehmann’s picture

Try it out? :-)

I like cookies!

vinoth.babu’s picture

If you are using field collection, you have to follow this,


$fc_ids = field_get_items('node', $node, 'field_alternative_titles');

 foreach ($fc_ids as $fc_id) {
    //Load the correct entity revisions. Note the conditions parameter is deprecated.

    $fc = entity_load('field_collection_item', $fc_id);
    $fc_res = $fc[$fc_id['value']];

     if (isset($fc_res->field_alternative_titles_title[LANGUAGE_NONE])) {
		$title = $fc_res->field_alternative_titles_title[LANGUAGE_NONE][0]['value'];
      }

}

I think this will help you.

Eluchel’s picture

Hey @vinoth.babu,
In your if statement you are checking if isset($fc_res->field_alternative_titles_title[LANGUAGE_NONE]) and then pulling a title from the value if it is set. Can I use this same code to populate the field_alternative_titles_title field? Maybe doing something like:

if (!isset($fc_res->field_alternative_titles_title[LANGUAGE_NONE])) {
        $fc_res->field_alternative_titles_title[LANGUAGE_NONE][0]['value'] = $node->title;
      }

Would that populate the field_alternative_titles_title field?

Thank you! I think this is the closest I have gotten to a solution yet! :)