1

In drupal 8 I have created a bespoke content type... I now would like to create content of the bespoke content type via Php through user interaction. For example, the user clicks a button and it triggers a function in my module which I am creating.

I have used the following code:

$node = Node::create([
  'type'        => 'article',
  'title'       => 'My title',
   ]);
   $node->save();

Which does create content in the content area of the admin panel, but... The content type column is empty?

Am sure someone will all ready have done this type of thing before so any help will be most welcomed.

  • In which table? – user21641 Oct 27 '17 at 12:56
  • Sorry not sure how you mean at 'which table' ... that might be part of the problem =/ ... Will just need to create a page of type 'bespoke content type' – Mo-ster Oct 27 '17 at 13:00
  • Hm, I think I know what's happening...so I presume you are displaying the "content" in some table you have created on your page somewhere and the "type" of node is empty in your table(ie. not db). If so I think it is because you are trying to get the value of the "type" field as $node->type->value or something like that. But "type" field is entity reference which does not have "value" key but "target_id". Alternatively you can simply print $node->get('type')->first()->entity->label(); – user21641 Oct 27 '17 at 13:04
  • You should use the method to get the type for Node, which is getType(). api.drupal.org/api/drupal/core!modules!node!src!Entity!Node.php/… – Kevin Oct 27 '17 at 13:17
  • Regarding the type, you cannot create types on the fly like this if that is what you are asking. They have to exist first in Drupal. That would be my guess as to why it is empty. – Kevin Oct 27 '17 at 13:20
1

Thanks Ivan Jaros and Kevin ... Once I placed the machine name of the content type (rather than it's human readable title) as the type value the content created successful and was of the required type e.g.

$node = Node::create([
    'type'        => 'the machine name associated with the content type',
    'title'       => 'My title',
   ]);
 $node->save();

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.