0

Hi i have 2 dropdownlsits:

 <?= $form->field($model, 'Rel_User')->widget(Select2::classname(), [
    'data' => ArrayHelper::map(UrUser::find()->orderby('Surname')->all(), 'Id', 'fullName'),
    'language' => 'pl',
    'options' => ['placeholder' => Yii::t('app', 'Wybierz użytkownika ...')],
    'pluginOptions' => [
        'allowClear' => true
    ],
]); ?>

    <?= $form->field($model, 'Rel_Category')->widget(Select2::classname(), [
    'data' => ArrayHelper::map(SmUserCategory::find()->orderby('Name')->all(), 'Id', 'Name'),
    'language' => 'pl',
    'options' => ['placeholder' => Yii::t('app', 'Wybierz kategorię ...')],
    'pluginOptions' => [
        'allowClear' => true
    ],
]); ?>

And i want to make one of them required if second of then is not selected. So if user not select both of them it should show message under two of them but if user select one it should save my model. I tried to do that with rules:

 [['Rel_User'], 'required', 'whenClient' => "function (attribute, value) {return $('#banner-rel_category input[type=dropdown]:checked').val() == null}"],
 [['Rel_Category'], 'required', 'whenClient' => "function (attribute, value) {return $('#banner-rel_user input[type=dropdown]:checked').val() == null}"],

but now 2 of then is all time required. What can i do to required one of then? my action create in ctrl

 public function actionCreate() {
            $model = new Banner();
            $model->scenario='create';
            if ($model->load(Yii::$app->request->post())) {
                $model->File = UploadedFile::getInstance($model, 'File');
                if ($model->save() && $model->upload() && $model->validate()) {
                    return $this->redirect(['view', 'id' => $model->Id]);
                }
            } else {
                return $this->render('create', [
                            'model' => $model,
                ]);
            }
        }

My rules now:

public function rules() {
        return [
            [['Url'], 'required'],
            [['File'], 'required', 'on' => 'create'],
            [['Rel_User'], 'my_required'],
            [['Rel_Category'], 'my_required'],
            [['Views', 'Rel_User', 'Rel_Category', 'CreatedAt', 'UpdatedAt', 'IsDeleted', 'Id'], 'integer'],
            [['Image', 'Url', 'Caption'], 'string', 'max' => 255],
            [['Url'], 'match', 'pattern' => '/^(http(s?):\/\/)?(www\.)?[a-zA-Z0-9\.\-\_]+(\.[a-zA-Z]{2,3})+(\/[a-zA-Z0-9\_\-\s\.\/\?\%\#\&\=]*)?$/'],
            [['File'], 'file', 'extensions' => ['gif', 'jpg', 'png', 'jpeg', 'JPG', 'JPEG', 'PNG', 'GIF'], 'checkExtensionByMimeType' => false,],
            [['CreatedAt', 'IsDeleted'], 'safe']
        ];
    }
qwerty
  • 101
  • 1
  • 10

1 Answers1

0

Use Custom validation in model:

public function rules()
{
  return [      
     [['Rel_User, Rel_Category'], 'my_required'],
  ];
}

public function my_required($attribute_name, $params)
{
   if (empty($this->Rel_User) && empty($this->Rel_Category)) 
   {
     $this->addError($attribute_name, Yii::t('app', 'At least 1 of the field must be filled up properly'));

    return false;
   }

   return true;
}

Reference

Community
  • 1
  • 1
Insane Skull
  • 9,220
  • 9
  • 44
  • 63
  • hmm now it not required both of dropdownlists – qwerty Mar 11 '16 at 10:08
  • i dont know why it not work or me I used this own rules before in other project and it work but now it not – qwerty Mar 11 '16 at 10:13
  • no it not, mahybe it controller fail but thers ruels whcich i have there work fine i show You my controller – qwerty Mar 11 '16 at 10:19
  • but i treid to move $model->validate() in all possible places and still not work – qwerty Mar 11 '16 at 10:22
  • @qwerty. remove both fields from required rule. – Insane Skull Mar 11 '16 at 10:25
  • i sorry i fix that :) so maybe You know where it can be a problem. I tried to use this funcion for example on other attribut and this still not work:`public function my_required($attribute_name, $params) { if (empty($this->Caption)) { $this->addError($attribute_name, Yii::t('app', 'Jedno z tych pól musi być wypełnione')); } }` – qwerty Mar 11 '16 at 10:38