Reputation: 9728
With the URL http://localhost/site/myAction?a[]=value1&a[]=value2
I'm trying to pass an array to an action. The controller action looks like this:
class SiteController extends Controller {
public function actionMyAction($a) {
...
}
}
I get the error:
exception 'yii\base\InvalidParamException' with message 'Variable declaration not valid.'
Actually, I'd like to be able to pass a string or an array of strings to the action. The single string works fine but not the array. How can I solve it?
Upvotes: 2
Views: 7830
Reputation: 11
compareList=[{"model":"shine"},{"model":"yamaha-alba"}]
using json encode data you can pass multiple value.
Upvotes: 1
Reputation: 9728
Passing a string and an array with the same declared parameter is not possible as it seems. To pass an array the parameter has to be declared this way:
class SiteController extends Controller {
public function actionMyAction(array $a) { // parameter must be an array now
...
}
}
With this a single parameter in the URL needs to be wrapped into an array within the URL.
An alternative is to declare no parameter at all and fetch the values with Yii::$app->request->get()
:
class SiteController extends Controller {
public function actionMyAction() { // no parameter anymore
$a = Yii::$app->request->get('a'); // $a can be an array or a string!
// or null if no argument was passed.
}
}
Now these URLs are valid:
http://localhost/site/myAction?a[]=value1&a[]=value2
http://localhost/site/myAction?a[]=value1
http://localhost/site/myAction?a=value1
http://localhost/site/myAction
Upvotes: 4