3

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.

7
  • Can't you just put the title in the $values array? Commented Mar 2, 2017 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. Commented Mar 2, 2017 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
    Commented Mar 2, 2017 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
    Commented Mar 2, 2017 at 4:05
  • These examples here are different than the one you posted: drupal.org/docs/7/api/entity-api/entity-metadata-wrappers
    – Kevin
    Commented Mar 2, 2017 at 4:07

1 Answer 1

7

This will work for you:

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

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

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

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