我需要讓我的自定義的驗證規則,以警告用戶電子郵件或phone_number
字段是必須的,但自定義驗證函數不叫Yii2自定義驗證函數
到目前爲止我的代碼: 型號
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']);
}
}
控制器動作
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,
]);
}
}
任何幫助嗎?
我編輯的代碼仍然沒有工作 –
兩件事情1)也顯示所有的型號代碼..?也顯示動作(控制器)代碼 – scaisEdge
我更新了我的問題檢查! –