1

From my experience, I believe Drupal8 treat Form API in BlockBase differently from FormBase Class, the below block doesn't seem to work. Do I have to do anything else to make Ajax Form work in Block? Please suggest. Maybe I need to #attach something? or do I have to do it non Drupal way by directly injecting jQuery into the code?

    class SearchBlock extends BlockBase
    {

        /**
         * {@inheritdoc}
         */
        public function build()
        {

            $build = array();
            $build['form'] = array(
                '#e' => 'form',
                '#method' => 'get'
            );

            $build['form']['q'] = array(
                '#e' => 'textfield',
                '#size' => 50,
                '#name' => 'q',
                '#ajax' => array(
                    'callback' => '::ajaxSearchSuggest',
                    'wrapper' => 'search-suggest',
                    'event' => 'keypress'
                ),
                '#default_value' => $_GET['q'],
                '#suffix' => format_string('<div style="search-suggest"></div>'),
            );
            $build['form']['submit'] = array(
                '#e' => 'button',
                '#attributes' => array('onclick' => 'return false;'),
                '#ajax' => array(
                    'callback' => '::ajaxSearchSuggest',
                    'wrapper' => 'search-suggest',
                    'event' => 'click'
                )
            );


            return $build;
        }

        public function ajaxSearchSuggest($form, FormStateInterface $form_state)
        {
            return array('#markup' => 'TEST'); 
        }
    }

1 Answer 1

0

You can only use the ::something shortcut for callbacks if your class is the form class, otherwise the form system doesn't know on which object that method should be called.

Instead, you need to use something like [$this, 'someMethod'] or make it a static method with ['full\classname', 'someMethod'].

Another thing that you need to be aware of is that the form structure and form values there will be in a different structure. Your form is inside a settings form element, but you shouldn't hardcode it and instead find our element through the submitted form element and the parents of it.

0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.