Jinu Joseph Daniel
Jinu Joseph Daniel

Reputation: 6291

Yii 2.0 $request->post() issues

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 the version_no.But when it is called as $request->post("version_no"), it is not returning anything (or $request->post("version_no",-1) returns the default value -1).

As per Yii 2.0 docs, the syntax is correct and should return the value of post parameter.

But why is it failing in my case.The post array has the parameter in it.But the function is not returning when called for an individual parameter value.

Upvotes: 3

Views: 2040

Answers (2)

arogachev
arogachev

Reputation: 33538

You can access nested $_POST array elements using dot notation:

\Yii::$app->request->post('CreateCourseModel.version_no', -1);

Model properties are grouped like that for massive assignment that is done via $model->load(Yii::$app->request->post()).

Depending on your needs maybe it's better use default value validator like that:

['version_no', 'default', 'value' => -1],

Upvotes: 4

Tony
Tony

Reputation: 5867

your parameters are in $_POST['CreateCourseModel']['version_no'] etc. with $request->post('version_no',-1) you trying to get $_POST['version_no'] which is not defined so it returns you -1. So to get version_no use

$data = $request->post('CreateCourseModel'); 
print_r($data['version_no']);

Upvotes: 5

Related Questions