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


i creating yii application in data being sent on post request server via rest calls. there no activeform coming in scenario, best approach validate data model class data being sent , after successful validation, saved db table.

i had gone through official docs didn't find related. inbuilt approach given activeform $model->validate(), wondering if there easy calling function data posted without activeform validate data model class.

i know can done isset($_post['somefield'] bit traditional approach & repeated each field (personally feel it's boring activity check if data posted in field , perform validation each field separately).

is there official doc missed? or if not given in doc, best approach?

suggest me create code magic..

okay, after doing more research found solution said problem 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() sets attribute values in massive way. here, created new object model class , sets attributes coming on post request.

once set attributes model class object, validate() them , save them directly in db calling save() applicable after successful validation.

however, must have send attributes per rules section of model (including primary key auto incremented values. can set them later if not sending on rest call $model->id=''). otherwise, validate() return false.

being more specific $model->load() returns true if data posted form(as per understood coding experience) fields set object of model class (see more here). load() automatically loads formname in background scenario set yii developers.

you may try doing $model->load(yii::$app->request->post()) data sent on rest call, return false because attributes not set.

i think have explained solution above said problem. point out in case wrong or not understandable.

i hope helps future readers same issue.


Comments