jerome
jerome

Reputation: 193

update a field-collection from a computed field

I'm able to retrieve the fields of the field collection attached to my content type, using codes like :

foreach ($entity->field_collection[LANGUAGE_NONE] as $line) {..}

or from an entity wrapper.

But I'm definitely unable to update the collection fields with values computed in the computed field, like I usually do with other CCK fields, like :

$entity->field_regular[LANGUAGE_NONE][0]['value'] = $value ;

then it is saved normally, as if I edited field_regular 'by hand'.

with collection this won't work (does nothing visible) :

$entity->field_collection[LANGUAGE_NONE][$key]['field_coll_field0'][LANGUAGE_NONE][0]['value'] = $value ;
// entity wrapper way
$coll = entity_load('field_collection_item', array($line['entity']->item_id));
$wcoll = entity_metadata_wrapper('field_collection_item', $coll[$key);
$wcoll->field_coll_field0->set($value) ;

any save() methods gives me a blank page (infinite cgi loop) :

entity_save('field_collection_item',$coll);
wcoll->save();

what should I know to programmatically save collection fields ? thanks, Jerome

Upvotes: 0

Views: 470

Answers (1)

kenorb
kenorb

Reputation: 166755

Please check Entity metadata wrappers doc page with simple example how to update a field collection, for example:

<?php
    // Populate the fields.
    $ewrapper = entity_metadata_wrapper('node', $node);
    $ewrapper->field_lead_contact_name->set($contact_name);
    $ewrapper->field_lead_contact_phone->set($contact_phone);
    $ewrapper->field_lead_contact_email->set($contact_email);  

    // Create the collection entity and set it's "host".
    $collection = entity_create('field_collection_item', array('field_name' => 'field_facilities_requested'));
    $collection->setHostEntity('node', $node);  

    // Now define the collection parameters.
    $cwrapper = entity_metadata_wrapper('field_collection_item', $collection);
    $cwrapper->field_facility->set(intval($offset));
    $cwrapper->save();  

    // Save.
    $ewrapper->save();
?>

So probably you need to do as below:

try {
  // Entity wrapper way.
  $coll = entity_load('field_collection_item', array($line['entity']->item_id));
  $wcoll = entity_metadata_wrapper('field_collection_item', $coll);
  $wcoll->field_coll_field0 = $value;
  $wcoll->save();
} catch (Exception $e) {
  drupal_set_message(t('Error message: @error.',
        array('@error' => $e->getMessage())), 'error');
  watchdog_exception('MYMODULE', $e);
}

Adding try/catch should prevent you from having a blank page. However if you've still an issue, check watchdog logs or any errors in PHP log file.

Upvotes: 0

Related Questions