I want to enable users to click a link to create a node of a specific content type. However, instead of going to /node/add/contenttype
, which is the standard Drupal flow, I want the node of the relevant content type to automatically be created and saved, and then redirect the user to the newly created node's edit page.
In other words, when a user clicks "add a node," I want to create the node for the user and send the user to the edit page.
I want to do this because I have a very long, complicated form and I want to use the Autosave Form module to automatically save the form; however, this module can only save a node/entity that has already been saved once (entities with an entity ID).
What's the simplest way to implement this?
I'm thinking that I will need to define a custom route that checks permission, runs code to create the node, and then redirects to the node.
EDIT: Overriding the NodeController
As suggested by 4k4, I overrode the NodeController as follows. However, the problem is that when I go to /node/add/contenttype
, the node is created and the form is shown, but it's an old form; when I try to save it, I get this error: "The content has either been modified by another user, or you have already submitted modifications. As a result, your changes cannot be saved."
class MymoduleNodeController extends NodeController {
public function add(NodeTypeInterface $node_type) {
$content_type = $node_type->id();
if ($content_type == 'MYTYPE') {
$node = $this->entityManager()->getStorage('node')->create([
'type' => $node_type->id(),
]);
$node->save();
$form = $this->entityFormBuilder()->getForm($node);
return $form;
}
else { // Default node creation behavior