0

I am trying to add a subscribe button as a block.

I added a form as

class SubscribeTag extends FormBase {

  public function buildForm(array $form, FormStateInterface $form_state) {

    $form['actions'] = [
      '#type' => 'actions',
    ];    

    $form['actions']['ajaxsubmit'] = [
      '#type' => 'submit',
      '#value' => 'Subsscribe',
      '#ajax' => [
        'callback' => '::ajaxSubmit',
        'wrapper' => 'message-wrapper',
      ],
    ];

    $form['messages'] = [
      '#type' => 'container',
      '#attributes' => ['id' => 'message-wrapper'],
    ];

    return $form;
  }

  public function getFormId() {
    return 'skb_subscription';
  }

  public function submitForm(array &$form, FormStateInterface $form_state) {

  }

  public function ajaxSubmit(array &$form, FormStateInterface $form_state) {
    drupal_set_message('Thank you for subscribing');
  }

}

It works correctly when a route is defined. When i go to the page /skb_subscribe_form the callback works correctly.

skb_subscription.subscribe:
  path: 'skb_subscribe_form'
  defaults:
    _form:  '\Drupal\skb_subscription\Form\SubscribeTag'
    _title: 'SKB Subscription'
  requirements:
    _permission: 'access content'

But when i try add the form to a block using the code

class SubscribeBlock extends BlockBase {
  public function build() {
    return \Drupal::formBuilder()->getForm("\Drupal\skb_subscription\Form\SubscribeTag");
  }
}

i get the following error "A fatal error occurred: The specified #ajax callback is empty or not callable."

I tried changing the callback with

$form['actions']['ajaxsubmit'] = [
      '#type' => 'submit',
      '#value' => 'Subsscribe',
      '#ajax' => [
        'callback' => '\Drupal\skb_subscription\Form\SubscribeTag::ajaxSubmit ',
        'wrapper' => 'message-wrapper',
      ],
    ];

but still getting the same error.

  • $build['form'] = \Drupal::formBuilder()->getForm('\Drupal\skb_subscription\Form\SubscribeTag'); return $build; and keep ajax callbaxk as 'callback' => '::ajaxSubmit', – Shreya Shetty Nov 14 '16 at 10:01
  • Welcome :) @ Deepak – Shreya Shetty Nov 14 '16 at 10:19
2

Try this

$build['form'] = \Drupal::formBuilder()->getForm('\Drupal\skb_subscription\Fo‌​rm\SubscribeTag');
 return $build; 

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.