Tuesday 12 March 2019

Create Custom Form on custom path programmatically Drupal 8

Form can be created in Drupal 7 & 8 with the help of Form API.

Create a form to add company with its details on a path "add/new/company". To do this we have to do 

  • Register path
  • Create form to add company
In Drupal 7, Path registration is done by hook_menu and form can be called on this path with the help of function "drupal_get_form" in page callback of this hook_menu.

<?php 
/** 
  * Implementation of hook_menu 
  */
function firstcustommodule_menu() {
$items = array();
$items['add/new/company'] = array(
    'title' => t('Add New Company'),
    'page callback' => 'drupal_get_form',
    'page arguments' => array('add_company_info_form'),
    'access callback' => TRUE,
    'type' => MENU_CALLBACK,
  );
  return $items;
}
Now company add form in "add_company_info_form"
<?php
function add_company_info_form() {
  $form['company_name'] = array(
    '#title' => t('Company Name:'),
    '#type' => 'textfield',
    '#default_value' => '',
    '#maxlength' => 60,
    '#required' => TRUE,
  );

  $form['company_email'] = array(
    '#title' => t('Company Email:'),
    '#type' => 'textfield',
    '#default_value' => '',
    '#maxlength' => 60,
    '#required' => TRUE,
  );

  $form['telephone'] = array(
    '#title' => t('Tel:'),
    '#type' => 'textfield',
    '#default_value' => '',
  );
  $form['address'] = array(
    '#title' => t('Address:'),
    '#type' => 'textfield',
    '#default_value' => '',
  );

  $form['submit'] = array(
    '#type' => 'submit',
    '#value' => t('Save'),
  );

  return $form;
}

In Drupal 8, Create a route in routing file and create a form. Then call this form on this route.
firstcustommodule.routing.yml
firstcustommodule.company_add:
  path: 'company/add/new'
  defaults:
    _form: '\Drupal\firstcustommodule\Form\CompanyAddForm'
    _title: 'Add New Company'
  requirements:
    _permission: 'access content'

defaults: Defines default property of route.
_form:
A class name implementing Drupal\Core\Form\FormStateInterface. This defines the form which is to render on the above route.
_controller:
This can be callable function or service which will return a rederable array or Symfony\Component\HttpFoundation\Response object.

Now create a directory in Form in custom module > src.
In Form directory create a file named: CompanyAddForm.php.This file having CompanyAddForm class.

<?php

/**

 * @file
 * Contains \Drupal\firstcustommodule\Form\CompanyAddForm
 */

namespace Drupal\firstcustommodule\Form;


use Drupal\Core\Form\FormBase;

use Drupal\core\Form\FormStateInterface;

/**

 * Provides company add form.
 */
class CompanyAddForm extends FormBase {
  /**
   * {@inheritdoc}
   */
  public function getFormId() {
    return 'company_add_form';
  }

  /**

   * {@inheritdoc}
   */
  public function buildForm(array $form, FormStateInterface $form_state) {
    // Form fields.
$form['company_name'] = array(
    '#title' => $this->t('Company Name:'),
    '#type' => 'textfield',
    '#default_value' => '',
    '#maxlength' => 60,
    '#required' => TRUE,
  );
  $form['company_email'] = array(
    '#title' => $this->t('Company Email:'),
    '#type' => 'textfield',
    '#default_value' => '',
    '#maxlength' => 60,
    '#required' => TRUE,
  );
  $form['telephone'] = array(
    '#title' => $this->t('Tel:'),
    '#type' => 'textfield',
    '#default_value' => '',
  );
  $form['address'] = array(
    '#title' => $this->t('Address:'),
    '#type' => 'textfield',
    '#default_value' => '',
  );
  $form['submit'] = array(
    '#type' => 'submit',
    '#value' => $this->t('Save'),
  );
  return $form;
  }

 /**

   * {@inheritdoc}
   */
  public function submitForm(array &$form, FormStateInterface $form_state) {
// To save company information, we need to create a custom table with the
// help of hook_schema in .install file.

   // To save company information in custom table.
   // Use of database service.
   $database = \Drupal::database();
   // Insert query.
   $insert = $database->insert('company_information')
    ->fields(
      [
        'company_name' => $form_state->getValue('company_name'),
        'company_email' => $form_state->getValue('company_email'),
        'company_address' => $form_state->getValue('address'),
        'company_telephone' => $form_state->getValue('telephone'),
        'created' => time(),
      ]
    )->execute();
   if ($insert) {
     drupal_set_message($this->t('Company information has been saved successfully'));
   }
  }
}

Save above file and clear cache.
Now hit the url "company/add/new". The created form will be available to appear as in screenshot.














Now a look to above custom form class "CompanyAddForm".
CompanyAddForm : this class is extending the "FormBase" class. FormBase class says to implement following methods.
getFormId(): This method return the form id.
buildForm(): This method return the $form with form fields.
submitForm(): This method submits the form.

No comments:

Post a Comment