我昨天发布了一个关于单选按钮Textfield Mandatory On Radio Button的自定义验证的问题。我得到了答案。但是,这不是确切的答案。但是,它解决了我的一个问题。
实际上,我有 2 个单选按钮。
- 个人
- 公司
When, Radio Button having "Individual" value is selected, CompanyName textbox should not be mandatory. But, when Radio Button having "Firm" value is selected, CompanyName textbox should be mandatory.
现在发生的事情是,当我选择单选按钮“公司”并且没有为 CompanyName 文本框填充任何值时,数据没有插入到数据库表中。美好的。这没关系。但是,错误消息未以形式显示。选择 Radio Button Firm 后,错误消息应显示为 CompanyName 文本框是必需的。
我没有得到我做错的地方。这是我的视图、控制器和模型代码。请帮我。
register.php (查看)
<?php
use yii\helpers\Html;
use yii\bootstrap\ActiveForm;
use yii\captcha\Captcha;
use yii\bootstrap\Modal;
use yii\helpers\Url;
?>
<?php $form = ActiveForm::begin(['id' => 'register-form']); ?>
.
.
.
<?= $form->field($model, 'AdminType')
->radioList(array('Individual'=>'An Individual', 'Firm'=>'Firm/Company'))
->label('Are You')?>
<?= $form->field($model, 'CompanyName')->textInput()->label('Company Name')->error() ?>
.
.
<?php ActiveForm::end(); ?>
SiteController.php(控制器)
<?php
namespace app\controllers;
use Yii;
use yii\filters\AccessControl;
use yii\web\Controller;
use yii\filters\VerbFilter;
use yii\swiftmailer\Mailer;
use app\models\RegisterForm;
public function actionRegister()
{
// Register Model
$model = new RegisterForm();
if ($model->load(Yii::$app->request->post()))
{
$post = Yii::$app->request->post('RegisterForm');
if ($model->validate())
{
}
else
{
// HERE YOU CAN PRINT THE ERRORS OF MODEL
echo "<pre>";
print_r($model->getErrors());
echo "</pre>";
}
return $this->refresh();
}
}
RegisterForm.php (模型)
<?php
namespace app\models;
use Yii;
use yii\base\Model;
use kartik\password\StrengthValidator;
class RegisterForm extends Model
{
public $fname;
public $lname;
public $email;
public $password;
public $confirmPassword;
public $AdminType;
public $CompanyName;
public $verifyCode;
public function rules()
{
return [
[['fname','lname', 'email', 'password','confirmPassword','verifyCode','AdminType'], 'required'],
['email', 'email'],
['confirmPassword', 'compare', 'compareAttribute' => 'password'],
['verifyCode', 'captcha'],
//add rule that uses the validator function
['AdminType','radioValidator'],
];
}
//implement the validator
public function radioValidator($attribute)
{
if($this->$attribute === 'Firm')
return $this->addError('CompanyName', 'Company Name cannot be blank');
}
}