Yii2:如何删除视图中的必需属性?

Yii2: how to remove required attribute in a view?

我有一个在其模型中按要求定义的文本字段。但是不需要视图。我尝试通过这种方式删除 required 属性,但它不起作用:

<?= $form->field($model, 'city')->textInput(['required' => false]) ?>

我需要在 view 或其 controller 中更改它。但不在其 model 中(因为其他视图需要 required 属性。)。

我知道如何使用 jQuery,但我更喜欢使用 PHP/Yii2

更新(@Muhammad Omer Aslam 的帮助需要):

actionUpdate($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,
    ]);

}

您可以使用 scenarios 为特定视图设置字段为必填项或非必填项。您可以分配场景所需的活动字段,这些字段将作为验证对象。

我假设模型是 Profile。在下面的示例中,默认情况下需要 firstnamelastnamecity

一个模型可能在不同的场景下使用,默认使用场景default。假设在您的情况下,我们可以声明一个只需要 firstnamelastname 的场景 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;
    }
}

然后在您的 controller/action 中,对于您不希望需要 city 字段的视图,初始化 Profile 模型对象如下

public function actionProfile(){
    $model = new \common\models\Profile(['scenario'=> \common\models\Profile::SCENARIO_SPECIAL]);
    return $this->render('profile',['model'=>$model]);
}

现在,如果您在此视图中提交表单,它将仅询问 firstnamelastname,而在您之前的 forms/views 中,如果您尝试提交表单,它将询问您在尝试提交时提供 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,
    ]);

}

转到模型并删除属性

public function rules()
{
    return [
        [['id_person', 'city'], 'required'], 
        [['id_person'], 'required'],
    ];
}

EX:

public function rules()
{
    return [
        [['id_person'], 'required'], 
        [['id_person'], 'required'],
    ];
}