How to add custom field and custom submit handler to views exposed filter form in Drupal 8 and Drupal 9

Here we are going to discuss , how to add a custom field to already existing view exposed form. Also we will be adding a extra submit handler to view exposed filter form.

Here we will be saving value entered in custom filed to logs while user filtering the data.

I have already one view of basic page.

Also I Have added a filter filed and exposed it so that user can change values.

You can see below exposed form if you open view page.

So here we are going to add additional field programmatically.

So in your custom_module.module file create below hook.

function dn_studentslist_form_views_exposed_form_alter(&$form, \Drupal\Core\Form\FormStateInterface $form_state, $form_id) {
 
    
	//echo "<pre>";print_r($form);echo "</pre>";
    if ($form['#id'] == 'views-exposed-form-basic-page-list-page-1') {
		//echo "<pre>";print_r($form);echo "</pre>";
        $form['criteria']['#type'] = 'textfield';
		$form['criteria']['#attributes']['placeholder'] = 'Purpose of search';
        $form['criteria']['#weight'] = -10;
	  $form['criteria']['#size'] = 10;
	    
		$form['#submit'][] = 'article_filter_submit_handler';
    }
}

Here dn_studentslist is the custom module name.

You can print $form as below and get form id from $form[‘#id’]

echo “<pre>”;print_r($form);echo “</pre>”;

Also you can get form id from view source of browser as below.

Here we are creating text field called criteria addition to title field in filter form.

Also below line adds additional submit handler where we are saving criteria value in to logs.

$form[‘#submit’][] = ‘article_filter_submit_handler’;

Add below function in in you custom module .module file.

function article_filter_submit_handler($form, \Drupal\Core\Form\FormStateInterface $form_state)

{

// echo "Alter executed".$form_state->getValue('criteria');
 if($form_state->getValue('criteria') != ''){
	 $account = \Drupal\user\Entity\User::load(\Drupal::currentUser()->id());
	 $user = $account->get('name')->value;
	 \Drupal::logger('type')->info("Basic Search by ".$user. " Purpose of search ".$form_state->getValue('criteria'));
 }

}

So clear the cache, you can see custom text field in exposed form.

So by hitting Apply button you can see text field value is stored in logs messages in path /admin/reports/dblog

 

Get Free E-book
Get a free Ebook on Drupal 8 -theme tutorial
I agree to have my personal information transfered to MailChimp ( more information )
if you like this article Buy me a Coffee this will be an ispiration for me to write articles like this.

You may also like...