Choxx Choxx - 1 year ago 115
PHP Question

How to validate data with a Model by POST request sent over REST call(without ActiveForm) - Yii2

I am creating a Yii application in which data is being sent over

request to my server via REST calls. As there is no
coming in the scenario, what is the best approach to validate data with Model class for which data is being sent and after successful validation, it will be saved into db table.

I had gone through official docs but didn't find anything related. As inbuilt approach is given for
, I am wondering if something like this is there as easy as calling a function for the data posted without
to validate that data with my

I know it can be done with
but it is a bit traditional approach & to be repeated for each field (personally I feel it's a boring activity to check if data is posted in a field and then perform validation for each field separately).

Is there any official doc which I missed? Or if it is not given in doc, what would be the best approach?

Suggest me something to create code magic..

Answer Source

Okay, After doing some more research I found solution to the said problem as below:

    $model = new AppDetails();
    $model->setAttributes(Yii::$app->request->post(), false);
    if($model->validate() && $model->save())
        return true;
    return false;

As per Yii docs, setAttributes() does Sets the attribute values in a massive way. Here, I created new object for my model class and then sets attributes coming over post request.

Once I set the attributes to my model class object, I could then validate() them and also save them directly in db just calling save() applicable only after successful validation.

However, with this you must have to send all attributes as per rules section of your model (including primary key auto incremented values. Also you can set them later if you are not sending it over rest call like $model->id=''). Otherwise, validate() will return false.

Being more specific about $model->load() it returns true if data is posted from a Form(as per what I understood from my coding experience) with fields set with object of Model class (see more here). load() automatically then loads the formName in background scenario set by Yii developers.

You may try doing like $model->load(Yii::$app->request->post()) with data sent over REST call, It will always return false because attributes are not set.

I think I have explained solution to my above said problem. Do point out in case anything is wrong or not well understandable.

I hope it helps future readers with same issue.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download