1

I'm loading the edit node form in a block and I want to use Ajax to save the node.

class MyBLockNameBlock extends BlockBase{

  public function build() {
    //I find the $nid i want to display

    $entity = Node::load($nid);
    $form = \Drupal::service('entity.form_builder')->getForm($entity, 'default');

    $form['actions']['#type'] = 'actions';
    $form['actions']['submit'] = [
      '#type' => 'submit',
      '#value' => $this->t('Submit'),
      '#ajax' => [
      'wrapper' => $wrapper_id,
      'callback' => '::ajaxCallback',
     ],
   ];

   $block['form'] = $form;
   $block['#markup'] = $this->t('<h3>Project Plan</h3>');
   return $block;

  }

  public function validateForm(array &$form, FormStateInterface $form_state)
  {
    if($form_state->hasAnyErrors()){
      return $form;
    }
  }

  public function ajaxCallback(array &$form, FormStateInterface $form_state)
  {
     return $form;
  }
}

But it doesn't work. If I change the $form['actions']['submit'] to

$form['actions']['submit'] = [
  '#type' => 'submit',
  '#value' => $this->t('Submit'),
  '#attributes'   =>array('class' => array('btn btn-info use-ajax-submit')),
  '#ajax' => [
    'wrapper' => $wrapper_id,
    'callback' => '::ajaxCallback',
  ],
];

The Ajax works but it doesn't validate the form. Should I create the validation by myself for each field?

Also I tried ajax_form_entity module but even if the ajax works, reloads the form, doesn't clear the fields after submission and still doesn't validate.

Also I need an extra handler when the user clicks the submit button in order to update a field from an other form.

Any idea?

0

You cannot add elements to the form outside of the form definition. You are adding your form elements in your block class, which is why it's not working as you expect. If you want to alter the entity form, you'll need to use hook_form_alter() and add your ajax there.

  • Thank you! This works much better! Even thought when I use ajax, even if I have a validation error or I just submit the form it scrolls the page to the top. In My callback what I do for now is to return the $form. Should I do something else? – Ismini May 22 '17 at 12:08

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.