Drupal - Embed a "node add" form in a page

You can use:

module_load_include('inc', 'node', 'node.pages');
$form = node_add('nodetype');
print drupal_render($form);

Although Daniel Wehner's answer is absolutely correct and works, I wanted to add two common problems I faced with this approach and workarounds how I overcome those problems. First my code, then the explanations:

global $user;

module_load_include('inc', 'node', 'node.pages');

$node = (object) [
  'uid' => $user->uid,
  'name' => (isset($user->name) ? $user->name : ''),
  'type' => 'YOUR_NODE_TYPE',
  'language' => LANGUAGE_NONE,
];
$form = drupal_get_form('YOUR_NODE_TYPE' . '_node_form', $node);

print drupal_render($form)

Why I did it this way, instead of Daniel's simple node_add?

Problem 1: node_add() function changes the page title to Create 'node type', this is hard coded in the function.

Workaround 1: Instead of using node_add function, I've copied the code and removed the drupal_set_title. The above code is the same code as the node_add function, except from this one line.

Problem 2: In the embedded form some ajax functions didn't work. For example if you have a field that can have unlimited values, so that you have an 'Add another item' button, or if you have an upload file field in your form, they don't work.

Workaround 2: In your custom module, implement hook_menu_alter() for ajax call paths, and include node.pages.inc.

function YOURMODULE_menu_alter(&$items) {
  $items['file/ajax']['file path'] = drupal_get_path('module', 'node');
  $items['file/ajax']['file'] = 'node.pages.inc';
  $items['system/ajax']['file path'] = drupal_get_path('module', 'node');
  $items['system/ajax']['file'] = 'node.pages.inc';
}

Tags:

Forms

Nodes

7