How do I make yii2 ActiveForm ignore previous submitted values?

I am trying to create a simple search form (it will get more complex soon, so I am using ActiveForm here instead of just going through the GET parameters to an 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 am using $ formName = '' in the controller and 'name' => 'q' to make the query string cleaner (just q instead of UserSearchForm [q]).

Everything looks fine until it leaves. I see a hidden q field in the form and after the second view the url looks like / user? Q = value1 & q = value2, each adding another q to the hidden fields. Is there a good way to get rid of these hidden fields? Or maybe the whole approach is wrong? Anyway, I will need hidden fields (sorting, pagination, etc.).

+3


source to share


2 answers


You should just set the form action (if the current url is empty):



<?php $form = ActiveForm::begin([
    'id' => 'search-form',
    'method' => 'get',
    'action' => ['controller/index']
]); ?>

      

+6


source


If you are using the same action and controller for filtering as for displaying results, then



$form = ActiveForm::begin([
    'id' => 'filter-form',
    'method' => 'get',
    'action' => Url::toRoute(\Yii::$app->request->getPathInfo())
]);

      

0


source







All Articles