/** * Creates a new Contact model. * If no group or category exist will redirect to related creation page. * If creation is successful, the browser will be redirected to the 'view' page. * @return mixed */ public function actionCreate() { $model = new Contact(); $errorCode = 0; $categorie = Contact_category::getContact_category(); if ($categorie == null) { $errorCode = 1; } $gruppi = Contact_group::getGruppi(); if ($gruppi == null) { $errorCode = $errorCode + 2; } if ($errorCode > 0) { return $this->redirect(['create-group-or-category', 'errorCode' => $errorCode]); } if ($model->load(Yii::$app->request->post()) && $model->save()) { return $this->redirect(['view', 'id' => $model->id]); } else { /* passage of parameter $categorie to 'create' view, and then to '_form' partial */ return $this->render('create', ['model' => $model, 'categorie' => $categorie]); } }
<?php use yii\helpers\Html; use yii\widgets\ActiveForm; use yii\helpers\ArrayHelper; use common\models\Contact_group; use common\models\Contact_to_contact_group; /* @var $this yii\web\View */ /* @var $model common\models\Newrubrica */ /* @var $form yii\widgets\ActiveForm */ $gruppi = Contact_group::getGruppi(); ?> <div class="contact-form"> <?php $form = ActiveForm::begin(); ?> <?php echo $form->field($model, 'lastname')->textInput(['maxlength' => 255]); ?> <?php echo $form->field($model, 'firstname')->textInput(['maxlength' => 255]); ?> <?php echo $form->field($model, 'company')->textInput(['maxlength' => 255]); ?>
public function afterSave($insert, $changedAttributes) { $connection = \Yii::$app->db; $queryTuttiGruppi = $this->getContact_groups()->asArray()->all(); $arrayTuttiGruppi = ArrayHelper::map($queryTuttiGruppi, 'id', 'name'); // if not a new contact, delete all groups if (!$insert) { Contact_to_contact_group::deleteAll('contact_id = :id', [':id' => $this->id]); } $gruppiSelezionati = $this->gruppi; $gruppiScrittura = Contact_group::getGruppi(); // aggiunge i gruppi di cui fa parte il contatto e che non ho il permesso di modificare foreach ($arrayTuttiGruppi as $key => $value) { if (!array_key_exists($key, $gruppiScrittura)) { array_push($gruppiSelezionati, $key); } } $lenght = count($gruppiSelezionati); $contatti = array_fill(0, $lenght, $this->id); $gruppicontatti = array_map(null, $contatti, $gruppiSelezionati); $connection->createCommand()->batchInsert('contact_to_contact_group', ['contact_id', 'contact_group_id'], $gruppicontatti)->execute(); }