1

I need to make my custom validation rule to warn the user either email or phone_number field is required , but the custom validation function not called

my code so far : Model

namespace backend\models;
use Yii;


class Advertisement extends \yii\db\ActiveRecord
{
    /**
     * @inheritdoc
     */
    public static function tableName()
    {
        return 'advertisement';
    }

    /**
     * @inheritdoc
     */
    public function rules()
    {
        return [
            [['position', 'location', 'status'], 'required'],
            [['description'], 'string'],
            [[ 'phone_number', 'company'], 'integer'],
            [['created_at', 'updated_at','date_added'], 'safe'],
            [['position', 'email', 'location', ], 'string', 'max' => 255],
            [['phone_number','email'], 'myRule'],
        ];
    }


    public function myRule($attribute, $params)
    {

        if (empty($this->email)
            && empty($this->phone_number)
        ) {
            $this->addError($attribute, Yii::t('ap', 'either Phone or Email required'));

            return false;
        }

        return true;
    }

    /**
     * @inheritdoc
     */
    public function attributeLabels()
    {
        return [
            'id' => Yii::t('app', 'ID'),
            'position' => Yii::t('app', 'Position'),
            'description' => Yii::t('app', 'Description'),
            'email' => Yii::t('app', 'Email'),
            'phone_number' => Yii::t('app', 'Phone Number'),
            'created_at' => Yii::t('app', 'Created At'),
            'updated_at' => Yii::t('app', 'Updated At'),
            'company' => Yii::t('app', 'Company'),
            'status' => Yii::t('app', 'Status'),
        ];
    }

    /**
     * @return \yii\db\ActiveQuery
     */
    public function getCompany0()
    {
        return $this->hasOne(User::className(), ['id' => 'company']);
    }


}

controller action

 public function actionCreate()
 {
     $model = new Advertisement();

     if ($model->load(Yii::$app->request->post()) ) {
         $model->company = Yii::$app->user->identity->id;
         $model->created_at = date("Y-m-d H:i:s");
         $model->date_added = date("Y-m-d H:i:s");

          $model->save();
          return $this->redirect(['view', 'id' => $model->id]);
     } else {
            return $this->render('create', [
                'model' => $model,
            ]);
     }
 }

any help ?

2 Answers 2

3

You need to disable skipOnEmpty property of Validator for it .. For More Info Read

 Update your code as 

  [['phone_number','email'], 'myRule' ,'skipOnEmpty' => false],
Sign up to request clarification or add additional context in comments.

Comments

0

I think you hsold use $attribute and not $attribute_name

public function myRule($attribute_name, $params)
{

    if (empty($this->email)
        && empty($this->phone_number)
    ) {
        $this->addError($attribute, Yii::t('app', 'either Phone or Email required'));

        return false;
    }

    return true;
}

from yii2 doc

addError() public method Adds an error about the specified attribute to the model object.

This is a helper method that performs message selection and internationalization. public void addError ( $model, $attribute, $message, $params = [] )

Try this action create

public function actionCreate()
{
    $model = new Advertisement();

    if ($model->load(Yii::$app->request->post()) ) {
        if ($model->validate()) {


          $model->company = Yii::$app->user->identity->id;
          $model->created_at = date("Y-m-d H:i:s");
          $model->date_added = date("Y-m-d H:i:s");

          $model->save();
          return $this->redirect(['view', 'id' => $model->id]);
        }
        else {
        $errors = $model->errors;
        return $this->render('create', [
            'model' => $model,
        ]);
      }
    }  else {
       return $this->render('create', [
            'model' => $model,
        ]);
    }
}

1 Comment

Two things 1) show also all the model code ..? show also the action (controller) code

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.