官术网_书友最值得收藏!

Custom submit handlers

So, up to now, we have seen how other modules can make changes to our form. That means adding new form elements, changing existing ones, etc. But what about our validation and submit handlers (those methods that get called when the form is submitted). How can those be altered?

Typically, for the forms defined as we did, it's pretty simple. Once we alter the form and inspect the $form array, we can find a #submit key, which is an array that has one item—::submitForm. This is simply the submitForm() method on the form class. So, what we can do is either remove this item and add our own function, or simply add another item to that array:

/** 
 * Implements hook_form_FORM_ID_alter(). */ function my_module_form_salutation_configuration_form_alter(&$form, \Drupal\Core\Form\FormStateInterface $form_state, $form_id) { // Perform alterations. $form['#submit'][] = 'hello_world_salutation_configuration_form_submit'; } 

And the callback we added to the #submit array above can look like this:

/** 
 * Custom submit handler for the form_salutation_configuration form. 
 * 
 * @param $form 
 * @param \Drupal\Core\Form\FormStateInterface $form_state 
 */ 
function my_module_salutation_configuration_form_submit(&$form, \Drupal\Core\Form\FormStateInterface $form_state) { 
  // Do something when the form is submitted. 
} 

So, the cool thing is that you can choose to tack on your own callback or replace the existing one. Keep in mind that the order they are in located in that array is the order in which they get executed. So, you can also change the order if you want.

There is another case though. If the submit button on the form has a #submit property specifying its own handler, the default form #submit handlers we saw just now won't fire anymore. This was not the case with our form. So, in that situation, you will need to add your own handler to that array. Hence, the only difference is the place you tack on the submit handler. A prominent example of such a form is the Node add/edit form.

Finally, when it comes to the validation handler, it works exactly the same as with the submit handler, but it all happens under the #validate array key.

Feel free to experiment with altering existing forms and inspect the variables they receive as arguments. I strongly encourage you to become familiar with the common form data and keep the documentation on form elements close by (https://api.drupal.org/api/drupal/elements/8.7.x).

主站蜘蛛池模板: 新津县| 治多县| 新宁县| 沾益县| 灌南县| 永登县| 铜川市| 龙岩市| 焉耆| 萍乡市| 崇义县| 婺源县| 大埔县| 桐柏县| 皋兰县| 皮山县| 元氏县| 巫山县| 南宁市| 乡城县| 墨脱县| 闽侯县| 广宁县| 贺兰县| 乌拉特中旗| 宁波市| 错那县| 密云县| 泗洪县| 略阳县| 上蔡县| 太原市| 台中县| 星座| 南华县| 许昌市| 家居| 龙山县| 滦南县| 乌兰县| 武隆县|