Drupal 8 embed node form in custom page

Sat, 12/19/2015 - 13:41 -- meladawy

One more tips that are not well documented in Drupal 8 API. In this tutorial i'll go though with creating a custom module which by default create a new page that simply embeding node creation form 

Create the module files

1- Create a new folder in /module directory and name it custom_module
2- Create custom_module.info.yml file with the following definition

name: 'Our custom module'
description: 'However !'
core: 8.x
type: module

3- Add custom_module.routing.yml with the following details

    path: 'new/article'
        _controller: '\Drupal\custom_module\Controller\customModuleArticleController::content'
        _permission: 'access content'

4- create the following file & folders inside our module src/Controller/customModuleArticleController.php with the following code

* @file 
* Contains \Drupal\custom_module\Controller\customModuleArticleController.
namespace Drupal\custom_module\Controller ;
use Drupal\Core\Controller\ControllerBase ;
use Symfony\Component\HttpFoundation\Request;
use Drupal\Component\Utility\Html ;
class customModuleArticleController extends ControllerBase
    public function content(Request $request) {
        $type = node_type_load("article"); // replace this with the node type in which we need to display the form for
        $node = $this->entityManager()->getStorage('node')->create(array(
          'type' => $type->id(),
        // OPTIONAL - Set default values for node fields
        $node->set('field_age', "32") ;
        $node_create_form = $this->entityFormBuilder()->getForm($node);  
        return array(
            '#type' => 'markup',
            '#markup' => render($node_create_form),

Now, you can create new article from
"new/article" instead of "node/add/article"
Easy right !


How to embedd EntityForms in a custom Block?

I followed your tutorial and it works like a charm. (y) However When I created a custom block, I am able to embedd custom forms to it. However this method of adding entityforms in custom block doesn't work. Kindly guide.
I did this to add my custom forms into a custom block.

$form = \Drupal::formBuilder()->getForm('\Drupal\custom\Form\MycustomForm');

It worked and i am so glad with this solution just what i needed

Add new comment

Plain text

  • No HTML tags allowed.
  • Web page addresses and e-mail addresses turn into links automatically.
  • Lines and paragraphs break automatically.