7

I have an custom module with Block:

namespace Drupal\generator\Plugin\Block;

use Drupal\Core\Block\BlockBase;

class GeneratorBlock extends BlockBase {
    
    public function build() {
        $form = \Drupal::formBuilder()->getForm('Drupal\generator\Form\ProjektForm');
        
        return array(
          'form' => $form,
          '#attached' => array(
            'library' =>  array(
              'generator/generator-css'
            ),
          ),
        );

    }
} 

All it does is placing some From in there with additional .css file (from library). I can place this block via Admin -> Structure -> Block layout and it works fine.

What I want now is to load that block via Ajax (because I want to refresh the whole block in some cases). And by that I mean I want to load it into wrapper (like with $.load(...)) or get the content of the block in JS variable (not the whole page with block, but just the rendered block).

I've found the tutorial for Drupal 7 on drupal.org, but I failed to port it to Drupal 8.

1 Answer 1

7

You can use the #ajax attribute to load main part of the block via Drupal ajax.

namespace Drupal\generator\Plugin\Block;

use Drupal\Core\Block\BlockBase;
use Drupal\generator\Form\ProjektForm;

class GeneratorBlock extends BlockBase {

  public function build() {
    return array(
      'form_wrapper' => array(
        '#prefix' => '<div id="form-wrapper">',
        '#suffix' => '</div>',
        '#markup' => '',
      ),
      'load_form' => array(
        '#type' => 'button',
        '#value' => $this->t('Load form'),
        '#ajax' => array(
          'wrapper' => 'form-wrapper',
          'callback' => array(static::class, 'getForm'),
        ),
      ),
      '#attached' => array(
        'library' =>  array(
          'generator/generator-css'
        ),
      ),
    );
  }

  public static function getForm() {
    return \Drupal::formBuilder()->getForm(ProjektForm::class);
  }

} 
2
  • 1
    Nice solution. However, was wondering if there is a way to load this without the use of the button. Like render the block automatically after the page has been loaded fully. May 10, 2019 at 23:37
  • 1
    The easiest way would be to hide the button with css and trigger it with JavaScript when the page finished loading.
    – Eyal
    May 11, 2019 at 7:03

Your Answer

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

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