[Solved] Update view with Many To many relation

Hello,

I have three related tables:

providers

subcategories

prov_subc

Many providers may have many categories, then I think it is a many-to-many

I want to edit a provider can also edit the categories to which it belongs (In the same view)

In the provider model




    public function getProvSubcs()

    {

        return $this->hasMany(ProvSubc::className(), ['prsu_prov_id' => 'prov_id']);

    }



I got to show all the subcategories in the view as follows:




    foreach($model->provSubcs as $key => $subcategory ){

        echo $form->field($subcategory, 'prsu_id')->textInput(['maxlength' => true]);

    }



However not as save data and at the same time validate data in the provsubc lso model. can you help me, please?

Have a look at the guide: http://www.yiiframework.com/doc-2.0/guide-input-tabular-input.html

Hello, is great. You solved my problem. I will paste my code to future references:

In my Providers model:




...

use app\models\Providers;

use app\models\ProvSubc;

use yii\base\Model;

public function actionUpdate($id)

{

	$model = $this->findModel($id);

	$provsubc = ProvSubc::find()->where(['prsu_prov_id'=>$model->prov_id])->indexBy('prsu_id')->all();

	if ($model->load(Yii::$app->request->post()) && Model::loadmultiple($provsubc,Yii::$app->request->post()) && $model->validate($model) && Model::validateMultiple($provsubc)) { 

		$model->save(false);

		foreach($provsubc as $clave => $categoria ){

		    $categoria->save(false);

		}

	}

}



In the view:




    foreach($provsubc as $clave => $categoria ){

         echo $form->field($categoria, "[$clave]prsu_subc_id");

         echo $form->field($categoria, "[$clave]prsu_cate_id");

    }



Thank you very much!! I am very happy