- <?php
-
-
-
- namespace frontend\models;
-
- use Yii;
- use yii\base\Model;
- use common\models\UserProducer;
- use common\models\Producer;
- use yii\helpers\Html;
-
-
- class AddProducerForm extends Model
- {
-
- public $id_producer;
- public $code;
-
-
-
- public function rules()
- {
- return [
- ['id_producer', 'integer'],
- ['id_producer', 'required'],
- ['id_producer', function($attribute, $params) {
-
- $producer = Producer::findOne($this->id_producer);
- if (!$producer) {
- $this->addError($attribute, 'Ce producteur n\'existe pas.');
- }
-
- $userProducerExist = UserProducer::searchOne([
- 'id_user' => Yii::$app->user->identity->id,
- 'active' => 1
- ]) ;
-
- if ($userProducerExist) {
- $this->addError($attribute, 'Ce producteur est déjà sur votre tableau de bord.');
- }
- }],
- ['code', 'required', 'message' => 'Champs obligatoire', 'when' => function($model) {
- $producer = Producer::findOne($this->id_producer);
- if ($producer) {
- return strlen($producer->code);
- } else {
- return false;
- }
- }],
- ['code', function($attribute, $params) {
- $code = $this->$attribute;
- $producer = Producer::findOne($this->id_producer);
-
- if ($producer && strtolower(trim($code)) != strtolower(trim($producer->code))) {
- $this->addError($attribute, 'Code incorrect');
- }
- }],
- ];
- }
-
-
-
- public function attributeLabels()
- {
- return [
- 'id_producer' => 'Producteur',
- 'code' => 'Code',
- ];
- }
-
-
-
- public function add()
- {
- $producer = Producer::findOne($this->id_producer);
-
- $userProducerExist = UserProducer::searchOne([
- 'id_user' => User::getCurrentId(),
- 'active' => 0
- ]) ;
-
- if ($userProducerExist) {
- $userProducerExist->active = 1;
- $userProducerExist->save();
- } else {
- $userProducer = new UserProducer();
- $userProducer->id_user = User::getCurrentId();
- $userProducer->id_producer = $this->id_producer;
- $userProducer->credit = 0;
- $userProducer->actif = 1;
- $userProducer->save();
- }
-
- Yii::$app->session->setFlash('success', 'Le producteur <strong>' . Html::encode($producer->name) . '</strong> a bien été ajoutée à votre tableau de bord.');
- }
-
- }
-
|