Clear Advanced Search Form With Button (Super Simple)

This clears your advanced search form in admin.php views via ajax.

Say you searched the form and need to return back to default results you can just click the button and it resets the form.

this is assuming you are using the default admin.php search js which is this




<?php

Yii::app()->clientScript->registerScript('search', "

$('.search-button').click(function(){

	$('.search-form').toggle();

	return false;

});

$('.search-form form').submit(function(){

	$.fn.yiiGridView.update('companies-list-view', {

		data: $(this).serialize()

	});

	return false;

});

");

?>



make sure where it says companies-list-view above that is the id of your CGridView. If your code is default you won’t have to change anything.

Add the following button inside your view and add an id to your search form… that’s it!

[size="4"]Clearing Default Form[/size]


   <?php echo CHtml::submitButton('Clear Form' , array( 'onclick'=>'js:$("#search-form").trigger("reset");')); ?>

update: I ran into an issue when i had to have a hidden field on the search form and it wouldn’t clear it. so we can add to the onclick event to clear the hidden field with the other data as follows

[size="4"]Clearing Hidden Fields[/size]




<?php echo CHtml::submitButton('Reset Results' , array('class'=>'clear-form btn blue btn-lg', 'onclick'=>'js:$("#search-form").trigger("reset"); $("#' . CHtml::activeId($model,'contract_company_id') . '").val("");')); ?>



[size="4"]Clearing Select2 [/size]


<?php echo CHtml::submitButton('Reset Results' , array('class'=>'clear-form', 'onclick'=>'js:$("#search-form").trigger("reset"); $(function() { $("#s2id_Companies_type").select2("data", null)});')); ?>

You should be able to add an id to your hidden field and just clear it by the id. I couldn’t do it that way because of how my form is set up.

Just thought I’d share since i ran into that problem.

make sure the #search-form is the id of your form ie in your _search.php




<?php $form=$this->beginWidget('CActiveForm', array(

'action'=>Yii::app()->createUrl($this->route),

'method'=>'get',

'id'=>'search-form',

)); ?>



basically all it does is clear the form with the onclick event. Since it’s onclick it gets executed before the .search function that submits the form. Since the form is empty it will update it with default unfiltered results.

this will also work with clistview if you are using this wiki. Just make sure you set the id of the search form.