[英]how to use the “required” attribute in Yii booster radioButtonListRow
[英]Yii2: how to remove required attribute in a view?
我有一個在其 model 中按要求定義的文本字段。但是不需要視圖。 我嘗試通過這種方式刪除所需的屬性,但它不起作用:
<?= $form->field($model, 'city')->textInput(['required' => false]) ?>
我需要在視圖或其controller中更改它。 但不在其model中(因為其他視圖需要 required 屬性。)。
我知道如何使用jQuery來做到這一點,但我更喜歡使用PHP/Yii2 。
更新(@Muhammad Omer Aslam 的幫助需要):
我的 model 叫做Persons 。
我的觀點叫做_form 。
我的 controller 叫做PersonsControllers 。 它有更新 function:
動作更新($id):
public function actionUpdate($id)
{
$model = $this->findModel($id); // How to add my new scenario here?
if ($model->load(Yii::$app->request->post()) && $model->save()) {
return $this->redirect(['view', 'id' => $model->id_person]);
}
return $this->render('update', [
'model' => $model,
]);
}
您可以使用方案將特定視圖的字段設置為必填。 您可以分配方案所需的活動字段,這些字段將作為驗證的主題。
我認為模型是Profile
。 在以下示例中,默認方案中需要firstname
, lastname
和city
。
模型可以用在不同的場景中,默認情況default
使用場景default
。 假設在您的情況下,我們可以聲明僅需要firstname
和lastname
special
方案。 在模型中,您將為方案名稱聲明一個常量,然后重寫scenarios()
方法,將分配key=>value
對,並以數組形式將活動字段名稱傳遞給該value
。
namespace app\models;
use yii\db\ActiveRecord;
class Profile extends ActiveRecord
{
const SCENARIO_SPECIAL = 'special';
public function scenarios()
{
$scenarios = parent::scenarios();
$scenarios[self::SCENARIO_SPECIAL] = ['firstname', 'lastname'];
return $scenarios;
}
}
然后在您不希望需要city
字段的視圖的controller/action
內部,按如下所示初始化“ Profile
模型對象
public function actionProfile(){
$model = new \common\models\Profile(['scenario'=> \common\models\Profile::SCENARIO_SPECIAL]);
return $this->render('profile',['model'=>$model]);
}
現在,如果您在此視圖內提交表單,它將僅詢問firstname
和lastname
而在以前的表單/視圖中,如果您嘗試提交表單,它將要求您在嘗試提交時提供city
,而您沒有更改或添加其他形式的表格或規則。
當您嘗試更新記錄並且不希望在更新記錄時需要city
時,唯一的區別是可以分配如下所示的方案,因為您沒有為模型創建新對象。
$model->scenario=\common\models\Profile::SCENARIO_SPECIAL;
在模型中:
const SCENARIO_MYSPECIAL = 'myspecial';
public function rules()
{
return [
[['id_person', 'city'], 'required', 'on' => self::SCENARIO_DEFAULT],
[['id_person'], 'required', 'on' => self::SCENARIO_MYSPECIAL],
];
}
在控制器中:
public function actionUpdate($id)
{
$model = $this->findModel($id);
$model->scenario = 'myspecial';
if ($model->load(Yii::$app->request->post()) && $model->save()) {
return $this->redirect(['view', 'id' => $model->id_person]);
}
return $this->render('update', [
'model' => $model,
]);
}
go 到 model 並去掉屬性
public function rules()
{
return [
[['id_person', 'city'], 'required'],
[['id_person'], 'required'],
];
}
前任:
public function rules()
{
return [
[['id_person'], 'required'],
[['id_person'], 'required'],
];
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.