0

I'm trying to do something like this:

function create_content($type,$content){
  $node = entity_create('node', array('type' => $type));
  $emw_node = entity_metadata_wrapper('node', $node);
  $fields = field_info_instances("node",$type);
  foreach ($content as $field => $value){
    if (array_key_exists($field,$fields)){
      $type=field_info_field_by_id($fields[$field]['field_id'])['type'];
      if ($type=='link_field') {
        $emw_node->$field->url = $value;
      }
      else {
        $emw_node->$field = $value;
      }
    }
  }
  $emw_node->save();
  $id = $emw_node->getIdentifier();
  $emw_node->other_field = $id;
  $emw_node->save();
}

With the idea of copying the node id to another field. However, I get an error:

EntityMetadataWrapperException: Invalid data value given. Be sure it matches the required data type and format. Value at node(9999)->field_other_field: 9999. in EntityMetadataWrapper->set() (line 122 of /sites/all/modules/entity/includes/entity.wrapper.inc).

How do I do this properly, preferably while still using an entity metadata wrapper?

1

The problem can be with your field format. If your field other_field is a text field check what text format is set for it in admin/structure/types/manage/your_content_type/fields. EG: enter image description here

If it is different from the plain text format you have to assign an array as a value to your field. EG:

$emw_node->other_field = array('value' => $id, 'format' => 'filtered_html');

or just

$emw_node->other_field = array('value' => $id);

  • The thing is, all the fields affected by the line $emw_node->$field = $value; are text fields, and so is the other_field field. The content in $content for those fields arrives as strings, just like the result from $id = $emw_node->getIdentifier();. Nevertheless, I'm going to try your solution. – Ernst Jan 12 '17 at 9:20
  • Your solution worked (to my surprise), I used $emw_node->other_field = array('value' => $id);. Now there remains the enigma of why in one case I can simply assign the value of a text field as a string and in the other case I need to wrap it in an array. All those fields are set to allow only one value. – Ernst Jan 12 '17 at 9:54
  • As i have proposed in my answer check text format of your fields (plain text, full html etc.). Maybe it will help. – Andrew Nim Jan 12 '17 at 10:08
  • You're right. The other fields were set as plain text whereas other_field was set as token text. – Ernst Jan 15 '17 at 7:35

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.