I found out how to get a node creation form, but I want to display and modify it (e.g. delete some fields I don't need).

This is my code.

public function buildForm(array $form, FormStateInterface $form_state) {
  $entity = \Drupal::entityManager()->getStorage('node')->create(array(
    'type' => node_type_load('friterie')->id(),
  // OPTIONAL - Set default values for node fields
  // $entity->set('field_machine_name', "value");
  $node_create_form = \Drupal::service('entity.form_builder')->getForm($entity);

  // I can display it with this method, but I don't know how to delete
  // some fields.
  $form['friterie'] = array(
    '#type' => 'markup',
    '#markup' => render($node_create_form),
    '#prefix' => '<div id="friterie-form">',
    '#suffix' => '</div>'
  return $form;

I see two approaches here:

  1. You will have to use "hook_form_alter", or a more strict form alter (for example: hook_form_FORM_ID_alter()). You can remove any elements there (calling from you .module file).

  2. When you get back your form object ($node_create_form) which will be rendered later on, you could make changes on that specific object witt it's public methods! Just dpm, or kint the object (with devel module enabled), and you will able the find the right method to alter the form elements you are about to render.

Side note: I highly discourage you from using "\Drupal::..." static service calls. FormBase classes are implementing the ContainerInjectionInterface, which means, in public static create function you can pass the services you need. Read more on this here!


You may just set the #access attribute of your fields in $node_create_form to false. I.e. if you have a field called title in your form, just set

$node_create_form['title']['#access'] = false;

This will hide the field (see From API Ref - access). Additionally, I'd suggest not to use the #markup. Instead of this, wrap your 'friterie' as a #type => 'container' and handover the result of getForm as sub-render array.

You don't need the alter-hooks if you're on that api-level. If you don't know what fields you have in your $node_create_form you may look at the rendered html (the field classes in there), or use the devel module and dpm().

But dpm() (as dpr() and kint()) may be very chatty and load your browser with tons of data. So you may just file_put_contents the array_keys of $node_create_form to some tmp-file.

Regards, Rainer

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.