n Drupal 8 - Creating a custom form in a block | CodimTh

Please Disable Your Browser Adblock Extension for our site and Refresh This Page!

our ads are user friendly, we do not serve popup ads. We serve responsible ads!

Refresh Page
Skip to main content
On . By CodimTh
Category:

in this tuto, I'll show you how to create a basic form and rendering it into a block in Drupal 8.

Step 1

Lets create a custom form, add a file in mymodule/src/Form/NewsletterForm.php

<?php
namespace Drupal\mymodule\Form;

use Drupal\Core\Form\FormBase;
use Drupal\Core\Form\FormStateInterface;


class NewsletterForm extends FormBase
{
  /**
   * @return string
   */
  public function getFormId()
  {
    return 'newsletter_form';
  }

  /**
   * @param array $form
   * @param FormStateInterface $form_state
   * @return array
   */
  public function buildForm(array $form, FormStateInterface $form_state)
  {
    $form['email'] = array(
      '#type' => 'email',
      '#title' => t('Email'),
      '#required' => TRUE,
    );

    $form['actions']['#type'] = 'actions';
    $form['actions']['submit'] = array(
      '#type' => 'submit',
      '#value' => $this->t('Register'),
      '#button_type' => 'primary',
    );
    return $form;
  }

  /**
   * Form submission handler.
   *
   * @param array $form
   *   An associative array containing the structure of the form.
   * @param \Drupal\Core\Form\FormStateInterface $form_state
   *   The current state of the form.
   */
  public function submitForm(array &$form, FormStateInterface $form_state)
  {
    // TODO: Implement submitForm() method.
  }
}

 

Step 2

create a new file  mymodule/src/Plugin/Block/NewsletterBlock.php to display the form we created in step 1 as block

<?php
namespace Drupal\mymodule\Plugin\Block;
use Drupal\Core\Block\BlockBase;

/**
 * @Block(
 *   id = "newsletter_block",
 *   admin_label = @Translation("Custom Newsletter block"),
 *   category = @Translation("Custom Newsletter block")
 * )
 */
class NewsletterBlock extends BlockBase {
  /**
   * {@inheritdoc}
   */
  public function build() {
    $form = \Drupal::formBuilder()->getForm('Drupal\mymodule\Form\NewsletterForm');
    return $form;

//   or use this method
//    return [
//      '#theme' => 'mytheme',
//      "#form" => $form,
//      "#data" => $data,
//    ];
//
//    in mytheme.html.twig use {{ form }} and {{ data }}

  }
}

 

Next steps

  • Clear your Drupal 8 caches. To do this I use this Drush command: drush cr if you don’t currently use Drush, I highly recommend using it, or the Drupal Console.
  • Now, go back to your site, and you should be able to see the block you have just created. Simply place the block to a region and it should become visible.

custom form block

 

 

Riadh Rahmi

Senior Web Developer PHP/Drupal & Laravel

I am a senior web developer, I have experience in planning and developing large scale dynamic web solutions especially in Drupal & Laravel.

Web Posts

Search

Page Facebook