这就是我现在拥有的:
<a href="<?= Url::to([null, 'Shopping[q]'=>$model->q, 'Shopping[view]'=>$model->view, 'Shopping[sort]'=>'priceLow'])?>">
但随着我添加更多的链接和字段,我必须更新每个&每个环节。我正在寻找类似于我在Rails中所做的事情,在那里你可以列出所有属性并更新其中一个。
link_to 'action', model.attributes.merge{sort: 'priceLow'}
我找不到如何获得一个包含表单名称的属性数组。
http://www.yiiframework.com/doc-2.0/yii-base-model.html
Model::getAttributes()
或Model::toArray()
不将表单/型号名称作为键的一部分。
<? print_r($model->getAttributes()) ?>
Array ( [q] => toaster [sort] => [view] => )
您只需尝试:
<a href="<?= Url::to(array_merge([null], $model->getAttributes()) ?>">
在你的控制器中:
$model->load(Yii::$app->request->get(), '');
如果formName()为空,那么整个$data数组将用于填充模型。
阅读更多:http://www.yiiframework.com/doc-2.0/yii-base-model.html#load()-详细
好的,我找到了一种方法来保留表单名称并合并新参数,这样你就可以在同一页上有多个表单,但我会标记另一个答案,因为我可能会使用它,因为URL更干净,我只需要一个表单。
<? print_r([null, 'Shopping'=>$model->getAttributes()]) ?><br/>
<? print_r([null, 'Shopping'=>array_merge($model->getAttributes(), ['sort'=>'priceLow'])]) ?><br/>
<?= Url::to([null, 'Shopping'=>array_merge($model->getAttributes(), ['sort'=>'priceLow'])]) ?><br/>
将产生
Array ( [0] => [Shopping] => Array ( [q] => toaster [sort] => priceHigh [view] => ) )
Array ( [0] => [Shopping] => Array ( [q] => toaster [sort] => priceLow [view] => ) )
/aa/web/index.php?r=shopping%2Fsearch&Shopping%5Bq%5D=toaster&Shopping%5Bsort%5D=priceLow
注意到"sort"参数被重写了吗?如果你想推广它,你可以使用
<?= Url::to([null, $model->formName() => $model->attributes]) ?><br/>
以下是如何使用带有覆盖的简化参数。
<?= Url::to(array_merge([null], $model->getAttributes(), ['sort'=>'priceLow'])) ?>
但是您必须更改Model::formName()
,因为在生成像输入字段这样的表单元素时,它会根据模型对它们进行命名。
public function formName() {
return '';
}