Problems with Yii 2.0 $ request-> post ()
In my controller I have the following lines
$request = Yii::$app->request;
print_r($request->post());
echo "version_no is ".$request->post('version_no',-1);
The output is given below
Array
(
[_csrf] => WnB6REZ6cTAQHD0gAkoQaSsXVxB1Kh5CbAYPDS0wOGodSRANKBImVw==
[CreateCourseModel] => Array
(
[course_name] => test
[course_description] => kjhjk
[course_featured_image] =>
[course_type] => 1
[course_price] => 100
[is_version] => 1
[parent_course] => test
[version_no] => 1
[parent_course_id] => 3
[course_tags] => sdsdf
)
)
version_no is -1
So here the return value of post () contains version_no. But when called as $request->post("version_no")
, it returns nothing (or $request->post("version_no",-1)
returns the default -1).
As per Yii 2.0 docs, the syntax is correct and should return the value of the post parameter.
But why doesn't it work in my case. The post array has a parameter in it. But the function does not return when called for a single parameter value.
source to share
your parameters are in $_POST['CreateCourseModel']['version_no']
etc. using $request->post('version_no',-1)
you are trying to get $_POST['version_no']
which is undefined, so it returns you -1. Therefore, to use version_no
$data = $request->post('CreateCourseModel');
print_r($data['version_no']);
source to share
You can access nested array elements $_POST
using dot notation:
\Yii::$app->request->post('CreateCourseModel.version_no', -1);
Model properties are grouped in the same way as for a massive assignment that is done through $model->load(Yii::$app->request->post())
.
Depending on your needs, it might be better to use the default validator:
['version_no', 'default', 'value' => -1],
source to share