function ModalForm::buildForm
File
-
modules/form_api_example/src/Form/ModalForm.php, line 60
Class
- ModalForm
- Implements the ModalForm form controller.
Namespace
Drupal\form_api_example\Form
Code
public function buildForm(array $form, FormStateInterface $form_state, $nojs = NULL) {
$form['#attached']['library'][] = 'core/drupal.ajax';
$form['description'] = [
'#type' => 'item',
'#markup' => $this->t('This example demonstrates a form that can work as a normal multi-request form, or as a modal dialog using AJAX.'),
];
if ($nojs == 'nojs') {
$form['use_ajax_container'] = [
'#type' => 'details',
'#open' => TRUE,
];
$form['use_ajax_container']['description'] = [
'#type' => 'item',
'#markup' => $this->t('In order to show a modal dialog by clicking on a link, that link has to have class <code>use-ajax</code> and <code>data-dialog-type="modal"</code>. This link has those attributes.'),
];
$form['use_ajax_container']['use_ajax'] = [
'#type' => 'link',
'#title' => $this->t('See this form as a modal.'),
'#url' => Url::fromRoute('form_api_example.modal_form', [
'nojs' => 'ajax',
]),
'#attributes' => [
'class' => [
'use-ajax',
],
'data-dialog-type' => 'modal',
'data-dialog-options' => json_encode(static::getDataDialogOptions()),
'id' => 'ajax-example-modal-link',
],
];
}
if ($nojs == 'ajax') {
$form['status_messages'] = [
'#type' => 'status_messages',
'#weight' => -999,
];
}
$form['title'] = [
'#type' => 'textfield',
'#title' => $this->t('Title'),
'#required' => TRUE,
];
$form['actions'] = [
'#type' => 'actions',
];
$form['actions']['submit'] = [
'#type' => 'submit',
'#value' => $this->t('Submit'),
'#ajax' => [
'callback' => '::ajaxSubmitForm',
'event' => 'click',
],
];
if ($nojs == 'nojs') {
unset($form['actions']['submit']['#ajax']);
}
return $form;
}