Saving two content types with entity reference in one form

Tuesday, 30 September, 2014

The solution is to add fields from one content type to node form of another, but you should save them as separate nodes using hook_form_alter() and hook_node_insert(). To achieve this, you will have to create two content types.

First one is the content type which I renamed to “Schools”. It has basic input fields. The second one is “Education program”. We want to make a field type called “entity reference” but it doesn’t exist yet.

We need Entity Reference module in order to achieve this, it can be downloaded from here: https://www.drupal.org/project/entityreference

  1. Download
  2. Extract to /sites/all/contrib/
  3. Enable in Drupal administration

Create a field called “school reference”. Name the field type “entity reference” and use any widget you want. It is not important because we won’t display this field in our form. We’ll add reference pro-grammatically.

Configure field and set Target type to “Node”, Entity selection mode to “Simple (with optional filter by bundle)” and Target bundle to “school”.

Now we have two separate content types and it’s time to do some Drupal magic. We will create a custom module, and call it “my_node_actions”.

Create folder with the same name in /sites/all/modules/custom/ directory and inside of my_node_actions/ create a file called “my_node_actions.module”.

This will be a file with both hooks.

Create new hook called “my_node_actions_form_alter”. This hook performs alterations before a form is rendered which allows us to add fields.

Check machine names of fields in education program content type we made in /admin/structure/types/manage/education-program/fields.

When user loads “school_node_form”, it will have 2 new fields we just added.

Next step is to save those two fields as separate node of type “Education program” and entity reference to school created with “school_node_form”.

It is achieved with “hook_node_insert”. This hook is invoked from “node_save()” AFTER the database query that will insert the node into the node table is scheduled for execution.

 

If you have followed this tutorial well, we have now successfully created two content types – School and Education program with an entity reference to that school.

 

Ana Lozančić

Ana is a content Marketing specialist and blogger. She graduated in Faculty of humanities and social sciences. She enjoys learning and applying knowledge about marketing and social media, covering latest trends and topics about software development subjects.

    Comments

    © 2017, All Rights Reserved