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 article, I'll show you how to create custom Simple Form in Drupal 8 programmatically.

This example demonstrates the different simple input elements that are used to collect data in a form.

 

codimth_form_api.routing.yml

codimth.form_api:
  path: '/codimth-simple-form'
  defaults:
    _form:  '\Drupal\codimth_form_api\Form\CodimthSimpleForm'
    _title: 'Codimth Simple Form Api'
  requirements:
    _permission: 'access content'

src/Form/CodimthSimpleForm.php

this class contains : 

getFormId(): This needs to return a string that is the unique ID of your form. Namespace the form ID based on your module's name.

buildForm(): This returns a Form API array that defines each of the elements of your form.

submitForm(): collect data and do things, like save the data to the database, send an email, or any number of other operations.

validateForm(): used to validate the data that's being collected.

 

<?php

namespace Drupal\codimth_form_api\Form;

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

/**
 * Implements a codimth Simple Form API.
 */
class CodimthSimpleForm extends FormBase
{

  /**
   * @param array $form
   * @param FormStateInterface $form_state
   * @return array
   */
  public function buildForm(array $form, FormStateInterface $form_state)
  {
    // Item
    $form['description'] = [
      '#type' => 'item',
      '#markup' => $this->t('This example shows how to add some inputs'),
    ];

    // Textfield.
    $form['title'] = [
      '#type' => 'textfield',
      '#title' => $this->t('Title'),
      '#size' => 60,
      '#maxlength' => 128,
    ];

    // CheckBoxes.
    $form['test_checkboxes'] = [
      '#type' => 'checkboxes',
      '#options' => ['drupal' => $this->t('Drupal'), 'wordpress' => $this->t('Wordpress')],
      '#title' => $this->t('Are you developer :'),
    ];

    // Color.
    $form['color'] = [
      '#type' => 'color',
      '#title' => $this->t('Color'),
      '#default_value' => '#f0f0f0',
    ];

    // Date.
    $form['date'] = [
      '#type' => 'date',
      '#title' => $this->t('Date'),
      '#default_value' => ['year' => 2020, 'month' => 2, 'day' => 15],
    ];


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

    // Add a submit button
    $form['actions']['submit'] = [
      '#type' => 'submit',
      '#value' => $this->t('Submit'),
    ];

    // Add a reset button
    $form['actions']['reset'] = [
      '#type' => 'button',
      '#button_type' => 'reset',
      '#value' => $this->t('Reset'),
      '#attributes' => [
        'onclick' => 'this.form.reset(); return false;',
      ],
    ];

    return $form;
  }

  /**
   * @return string
   */
  public function getFormId()
  {
    return 'codimth_simple_form_api';
  }

  /**
   * @param array $form
   * @param FormStateInterface $form_state
   */
  public function validateForm(array &$form, FormStateInterface $form_state)
  {
    $title = $form_state->getValue('title');
    if (strlen($title) < 15) {
      $form_state->setErrorByName('title', $this->t('The title must be at least 15 characters long.'));
    }
  }

  /**
   * @param array $form
   * @param FormStateInterface $form_state
   */
  public function submitForm(array &$form, FormStateInterface $form_state)
  {

    $title = $form_state->getValue('title');
    $this->messenger()->addStatus($this->t('You specified a title of @title.', ['@title' => $title]));
  }

}

 

Demo

custom simple form api

 

Other useful render elements:

 

// Date-time.
'#type' => 'datetime'
// URL.
'#type' => 'url'
// Email.
'#type' => 'email'
// Number.
'#type' => 'number'
// Password.
'#type' => 'password'
// Password Confirm.
'#type' => 'password_confirm'
// Range.
'#type' => 'range'
// Radios.
'#type' => 'radios'
// Search.
'#type' => 'search'
// Select.
'#type' => 'select',
// Multiple values option elements.
'#type' => 'select',
'#multiple' => TRUE,
// Tel.
'#type' => 'tel'
// Details.
'#type' => 'details',
// tableselect
'#type' => 'tableselect',
// Textarea.
'#type' => 'textarea',
// Text format.
'#type' => 'text_format',
// Weight.
'#type' => 'weight',
// File.
'#type' => 'file',
// Manage file.
'#type' => 'managed_file',
// Image Buttons.
'#type' => 'image_button',
// Button.
'#type' => 'button',
// Extra actions for the display.
$form['actions']['extra_actions'] = [
  '#type' => 'dropbutton',
  '#links' => [
    'test_action' => [
      'title' => $this->t('Test Form'),
      'url' => Url::fromRoute('youroute.name'),
    ],
  ],
];

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 new form you have just created.
  • I hope you found this article useful. let me know if you have any questions and I’ll be happy to answer them.

 

 

Comments

Add new comment

Restricted HTML

Search

Page Facebook

Become a patron

If you need some help or you search a Drupal freelancer don't hesitate to contact us.

 

Contact Us

All the content is FREE but I still need your help

 

Become a patreon