How to manage 2 forms of same model in the same Controller?

Hello All!

My profile page have 3 forms:

  • Avatar form

  • User form

  • User Metadata form

Now, I have this working great with 2 and 3 in my controller (2 different models), but I dont know how I can manage when I send the avatar form (only updates avatar) or the user form (only updates email)

There are any way to control whats form is sent and then update the desired propertie or our model? Thanks.

This my actually working action:


public function actionIndex()

    {

        $model = Yii::$app->user->identity;

        $userMeta = PgcUsersMeta::findOne(['fk_user' => $model->id]);


        //Si queremos cambiar el email

        if ($model->load(Yii::$app->request->post()) && $model->update(true, ["email"])

        || ($userMeta->load(Yii::$app->request->post()) && $userMeta->update())) {

            Yii::$app->getSession()->setFlash('profile-Msg-OK', Yii::t("app","Generic_Changes_OK"));

            return $this->redirect(['index']);

        } else {

            return $this->render('index', [

                'model' => $model,

                'userMeta' => $userMeta,

            ]);

        }


    }

Hi Juanla,

I want to ask you what brought you there? I mean you might not normaly have this problem knowing that one form per page is usually sufficient.

Anyway, i yhink you should have three links to three pages both having a form. That way you can easilly handle the form submission.

Is that a solution for what you want to do??

Hello! I know that one form per page is enough, but the profile page that I am working on, have these options on same page. I think that I can make these getting the name of the submited properties, but I want to know if there are any way more clean that yii2 offres.

Thanks

For every form you can use different controller/action. For example, for image change you can use user/changeImage, and for data update you can use user/update. If you want to build everything in one function, then in your existing controller/action you can write something like




/**

Create your model in your controller. 

Load data from post into model

Validation ->optional

Upload the image

Save image

**/


$model = new AvatarModel();

if(isset($_POST['AvatarModel'])){//Check $_POST array

	$model->load(Yii::app->request->post())//Load data

	if($model->validate()){//validate

	//Image upload

    	$model->image = AvatarModel::getInstance($this, 'image');

    	$model->image->saveAs('your folder');

	}

	//In your view just print this new image, or show errors

}