I am trying to create content from a cron job with a custom node type that contains just a title and body; the content type is mycontent (for argument sake).

I am trying to use the Entity API module because apparently it is supposed to be simpler.

Working from examples, I wrote the following code.

$values = array(
    'type' => 'mycontent',
    'uid' => $user->uid
$entity = entity_create('node', $values);
$ewrapper = entity_metadata_wrapper('node', $entity);
$ewrapper->title->set('My Title');

Clearly I am missing something here because I get an exception (EntityMetadataWrapperException: Unknown data property title).

So I changed it to the following.

$values = array(
    'type' => 'mycontent',
    'uid' => $user->uid
$entity = entity_create('mycontent', $values);
$ewrapper = entity_metadata_wrapper('mycontent', $entity);
$ewrapper->title->set('My Title');

Now I get a different error, an obtuse Invalid data value given.

Why cannot I get the Entity API module to work as advertised?

The current user in this case is user 1, not the anonymous user. If I add the content using Drupal standard functions, it works. So I know I am not having a permission issue.

I looked at this example, to write my code, and then proceeded to google a lot.

  • Can't you just put the title in the $values array? – RaisinBranCrunch Mar 2 '17 at 3:49
  • Yes but if I do it does not save correctly. No node is created. I am not doing something right but have no idea what is wrong. I have added a link to the example page I was using. – DeveloperChris Mar 2 '17 at 3:58
  • In the second example you're trying to create an entity from a type that isn't defined (mycontent). Need to have a valid entity here, like node, user, commerce_order, etc. – Kevin Mar 2 '17 at 4:00
  • Also, unless you have special code, cron runs as anonymous user... but this code should definitely work, unless your node type does not have a title. You aren't using something like Title Field module or anything like that? Is "title" definitely a property of the node type or is it a field? – Kevin Mar 2 '17 at 4:05
  • These examples here are different than the one you posted: drupal.org/docs/7/api/entity-api/entity-metadata-wrappers – Kevin Mar 2 '17 at 4:07

This will work for you:

$node = new stdClass();
$node->title = "My title";
$node->type = "mycontent";
$node->uid = $user->uid; 
$node->status = 1;
$node = node_submit($node);

More details you can see at https://www.drupal.org/docs/7/howtos/create-a-node-in-code

| improve this answer | |

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.