0

I'm recreating my pages in Drupal 8 for a platform upgrade. One thing I've identified for this upgrade is the need for a workflow that creates multiple nodes before it's actually finished. If a user creates node of type A, it automatically creates a second node of Type be and auto-fills an entity reference field with whatever nid Node A was given. I'm HOPING this is something I Can create easily, through a form builder or something like that.

I'm not sure what the best option is for this, but I do need to find a way to simplify this workflow. I think I'll need rules a part of it, but I'm not sure at all one way or the other.

  • create node a, on save/submit create also node b with reference to a, is that what you want ? – GiorgosK Mar 18 '18 at 9:41
  • Pretty much yes. I'm basically setting it up for a story archive, where Node A is the front page that contains all the story meta-data, and Node B is Chapter 1. I want to prefile Node B with the Entity Reference information for Node A, and Preset the chapter field I use for organization as 1. I basically recreated the book module in Entity References and Views in Drupal 7. Now I'm recreating that work in Drupal 8 and am addressing issues I discovered since I originally did this. – CW Smith Mar 18 '18 at 18:13
  • One place to start would be hook_node_insert. – Kevin Mar 19 '18 at 18:06
  • That sounds like a custom module though. Do you think that this would require a custom module? I'm starting to wonder if maybe it could be handled through Rules or something of that nature. I'm not sure yet, but is that possible? – CW Smith Mar 20 '18 at 1:28
0

Here is a solution I came up with. Create a custom module and in your MODULENAME.module file implement hook_form_alter to add a custom submit handler MODULENAME_add_story

function MODULENAME_form_alter(&$form, &$form_state, $form_id) { 
  // if creating node of type A (article is machine name)
  if($form_id == 'node_article_form') {
    $form['actions']['submit']['#submit'][] = 'MODULENAME_add_story';
  }  
}

In the custom submit function create the referenced node and save the reference on the original node

function MODULENAME_add_story($form, $form_state) {

  $article = $form_state->getFormObject()->getEntity();
  $aid = $article->id();
  $uid = $article->getOwnerId(); 

  // Create node of type B (story is machine name)    
  $story = \Drupal\node\Entity\Node::create([
    'type'        => 'story',
    'title'       => 'New auto created story new',
    'uid' => $uid,
    //set other fields
  ]);
  $story->save();    

  //set the reference and save
  $article->field_stories[] = ['target_id' => $story->id()];
  $article->save();
}

So when you create node of type article a node of type story is also created and referenced from article.

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.