Reputation: 1110
I'm trying to make a simple search form (it will grow more complex soon so I'm using an ActiveForm here instead of simply passing GET parameters to the action method).
controller:
public function actionIndex()
{
$search_form = new UserSearchForm();
$search_form->load(Yii::$app->request->get(), $formName = '');
return $this->render('index', [
'search_form' => $search_form
]);
}
view:
<?php $form = ActiveForm::begin(['id' => 'search-form', 'method' => 'get']); ?>
<?= $form->field($search_form, 'q')->textInput(['name' => 'q']) ?>
<?= Html::submitButton('Search') ?>
<?php ActiveForm::end(); ?>
I'm using $formName = '' in controller and 'name' => 'q' in view to make the query string cleaner (simple q instead of UserSearchForm[q]).
Everything looks fine until first submit. I see a hidden q field in the form and after second submit the URL looks like /user?q=value1&q=value2, each submit adds another q to hidden fields. Is there a good way to get rid of those hidden fields? Or maybe the whole approach is wrong? I guess I'll need hidden fields there anyway (sorting, pagination etc).
Upvotes: 3
Views: 4095
Reputation: 7881
If you use for filtering the same action and controller as for displaying results, then
$form = ActiveForm::begin([
'id' => 'filter-form',
'method' => 'get',
'action' => Url::toRoute(\Yii::$app->request->getPathInfo())
]);
Upvotes: 0
Reputation: 25322
You should simply set form action (if empty it will be the current url) :
<?php $form = ActiveForm::begin([
'id' => 'search-form',
'method' => 'get',
'action' => ['controller/index']
]); ?>
Upvotes: 6