How to handle ajax modal validation and model create

In my thread here

I created a form that saves a main model and its related model all in the one form.

Works great, except that there was no validation on the form, as i’m opening it up as modal - this is a requirement due to my target user experience.

In order to get the validation working, i added the necessary ‘‘enableAjaxValidation’ => true,’ to the ActiveForm and now validation works, however each and every time it runs it tries to run the controllers create method !

The way it is working currently, is that as soon as all fields are filled in, it auto runs the create method and saves the models, without the user clicking the ‘create’ button, as you would normally do in a form.

To keep it simple (other thread has more detail) some semi-pseudocode of the logic in controller create:

if (model->load($request->post && property->load($request->post)


    if (property->validate)

        if (property->save)

           model->property_id = property->id

           if (model->validate)

              if (model->save)




So yeah, form will post on each field since i need ajax to validate the form.

How is this normally handled or how can i avoid the post running each time ?

I thought about simply adding a field to the create button, and simply check that it exists before trying the post and validation - but that is ugly because it would not validate via ajax still - it would validate only once you click the create button ?

I hope thats clear :)

See Ajax Validation

You have to add this block in order to tell controller to perform ajax validation

if (Yii::$app->request->isAjax && $model->load(Yii::$app->request->post())) {

    Yii::$app->response->format = Response::FORMAT_JSON;

    return ActiveForm::validate($model);


When multiple models are involved, you could write something like this:

if ($model->load($request->post && $property->load($request->post)


    $valid = $model->validate();

    $valid &= $property->validate();

    if ($valid) {

        $property->save(false);  // w/o validation

        $model->property_id = $property->id;

        $model->save(false);     // w/o validation


And for ajax validation, you can follow what Richard has suggested.

Also note that ActiveForm::validate() can accept multiple models.

i thought of doing something like this but i was concerned that i would then have to remove the property_id from the rules of $model, and therefore compromise that validation ?

Or would you then maybe do a separate manual validation on that field just before save ?

I think you can make use of "scenario".

property_id must be validated for updating scenario, but not for creating.