简体   繁体   中英

Yii2 Custom Validation function not called

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 ?

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

 Update your code as 

  [['phone_number','email'], 'myRule' ,'skipOnEmpty' => false],

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,
        ]);
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM