简体   繁体   中英

How do I turn a form into a link in Yii?

This is what I have now:

<a href="<?= Url::to([null, 'Shopping[q]'=>$model->q, 'Shopping[view]'=>$model->view, 'Shopping[sort]'=>'priceLow'])?>">

But as I add more links and more fields, I have to update each & every link. I'm looking for something like I would do in Rails where you can just list all the attributes and update one of them.

link_to 'action', model.attributes.merge{sort: 'priceLow'}

I can't find how to get an array of attributes with the form name in it.

http://www.yiiframework.com/doc-2.0/yii-base-model.html

Model::getAttributes() or Model::toArray() doesn't include the form/model name as part of the keys.

<? print_r($model->getAttributes()) ?>
Array ( [q] => toaster [sort] => [view] => )

You should simply try :

<a href="<?= Url::to(array_merge([null], $model->getAttributes()) ?>">

And in your controller :

$model->load(Yii::$app->request->get(), '');

If formName() is empty, the whole $data array will be used to populate the model.

Read more : http://www.yiiframework.com/doc-2.0/yii-base-model.html#load()-detail

Ok I found a way to keep the form name and merge the new parameters so you can have multiple forms on the same page, but I'll mark the other answer because I'll probably use that since the URLs are cleaner and I only need one form.

<? 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/>

Will yield

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

Notice the 'sort' parameter overridden? If you want to generalize it, you can use

<?= Url::to([null, $model->formName() => $model->attributes]) ?><br/>

And here is how to use simplified parameters with overriding.

<?= Url::to(array_merge([null], $model->getAttributes(), ['sort'=>'priceLow'])) ?>

But you have to change the Model::formName() because when generating form elements like input fields, it will name them based on the model.

public function formName() {
  return '';
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM