Some Tips of the drupal 8 form API.
- How to add something just after a input ?
- How to make a collapsible field set ?
- How to Add a custom Validator / Submitter?
- How to use multiple submit buttons ?
Some Tips of the drupal 8 form API.
(#field_prefix and #field_suffix).
Example:$form['fieldname'] = array(
 '#type' => 'input',
 '#title' => t('The Label'),
 '#prefix' => '<span>Your HTML Just Before</span>'
 '#suffix' => '<span>Your HTML Just After</span>'
);
Add HTML just after a input, select, textarea ... (#field_prefix and #field_suffix)
Example:$form['fieldname'] = array(
 '#type' => 'input',
 '#title' => t('The Label'),
 '#field_prefix' => '<span>Your HTML Just Before input</span>'
 '#field_suffix' => '<span>Your HTML Just After input</span>'
);
Drupal 8 use HTML5 details tag and "OPEN" attribute to make a collapsible fieldset. Example:$form['filters'] = array(
 '#type' => 'details',
 '#title' => 'Filters',
 '#open' => FALSE,
);
Add a custom Validator / Submitter
Step 1. Create your Validator method
public function validateFormCustom(array &$form, FormStateInterface $form_state) {
 //Your validation codes
}
Step 2. Add this validator to your form.
$form['#validate'][] = '::validateFormCustom';
Step 1. Create several submit buttons and add custom submitter to each buttons (If you add nothing, it use the default submit method):
$form['actions']['submit_apply'] = [
 '#type' => 'submit',
 '#value' => t('Apply'),
];
$form['actions']['submit_reset'] = [
 '#type' => 'submit',
 '#value' => t('Reset'),
 '#submit' => array('::submitFormReset'),
];
Step 2. Then create your custom submit functions like:
public function submitForm(array &$form, FormStateInterface $form_state) {
 drupal_set_message("Apply");
 $form_state->setRebuild(TRUE);
}
public function submitFormReset(array &$form, FormStateInterface $form_state) {
 drupal_set_message("Reset");
 $form_state->setRebuild(FALSE);
}
Â
Use the "#tree" => TRUE configuration.Example :
 $form["test_field"]["#tree"] = TRUE;
 $form["test_field"][] = array(
       "#type" => "textfield",
       "#title" => "Title 1",
   );
 $form["test_field"][] = array(
       "#type" => "textfield",
       "#title" => "Title 2",
   );
Â
$form['fieldname'] = array(
 '#type' => 'text_format',
 '#title' => t('WYSIWYG Text field'),
 '#format' => 'full_html' //the default format used for editor.
);
A 'container' allow to hold fields, markup ... or to group of fields with all advantages of the api field element.
Example : Add the states visible to a type markup.$form['the_container'] = [
 '#type' => "container",
 '#prefix' => "<div class='text'>",
 '#suffix' => "</div>",
 '#states' => ['visible' => ['select[name="type"]' => ['value' => '1'],],],
];
$form['the_container']['markup'] = [
 '#markup' => "A text",
];
Example of number field on drupal 8 :$form['count'] = [
 '#type' => 'number',
 '#title' => 'A Number',
 '#step' => 2,
 '#min' => 1,
 '#max' => 10,
 '#required' => TRUE,
 '#default_value' => 4,
];
Comments