How to render form in drupal 8

Create custom form

namespace Drupal\mymodule\Form;

use Drupal\Core\Form\FormBase;

use Drupal\Core\Form\FormStateInterface;

class ExampleForm extends FormBase {

public function getFormId() {

// Unique ID of the form. return 'example_form';

}

public function buildForm(array $form, FormStateInterface $form_state,$param=null) {

// Create a $form API array.

$form['phone_number'] = array(

'#type' => 'tel',

'#value' => $param,

'#title' => $this ->t('Your phone number'),

);

$form['submit'] = array(

'#type' => 'submit',

'#value' => $this ->t('Save'),

);

return $form;

}

public function validateForm(array &$form, FormStateInterface $form_state) {

// Validate submitted form data.

}

public function submitForm(array &$form, FormStateInterface $form_state) {

// Handle submitted form data.

}

}

 

Render Custom form

 

$param = '612-123-4567';

$form = \Drupal::formBuilder()->getForm('Drupal\mymodule\Form\ExampleForm', $param);

Add new comment

Plain text

  • No HTML tags allowed.
  • Lines and paragraphs break automatically.
  • Web page addresses and email addresses turn into links automatically.