【问题标题】:ActiveForm Name in yii2yii2 中的 ActiveForm 名称
【发布时间】:2015-09-09 19:45:41
【问题描述】:

我正在使用Yii2ActiveForm
在正常情况下,如果ActiveForm 中的任何输入被使用,输入的名称应该与ActiveRecord 属性相同,这是数据库中相关表的列的名称。

出于某种原因,我想使用 Active TextArea,它的名称也与 Active Record 属性不同。实际上我想获取 TextArea's 值并分解然后保存到数据库。

有没有办法使用名称与 ActiveRecord 属性不同的 ActiveInput?

查看:

<?php $form = ActiveForm::begin([
             'id'=>'import-student',
             'options'=>[
                 'class'=>'form-horizontal',
                 'enctype'=>'multipart/form-data']
             ]); ?>    

    <?= $form->field($model, 'first_name', ['inputOptions'=>[
                             'placeholder'=>'import Users as text']])
             ->textArea(['rows'=>'12','class'=>'form-control'])
             ->label(false); ?>  
    <?= Html::submitButton('Submint', ['class'=>'btn btn-primary']) ?> 

<?php ActiveForm::end(); ?>  

控制器:

public function actionImport()
{
    $model = new Student();

    if ($model->load(Yii::$app->request->post()) && $users = $model->saveTextArea()) {
        Yii::$app->session->setFlash('info', print_r($users));
    } 

    return $this->render('import',[
        'model'=>$model,
    ]);
}

型号:

public function attributeLabels()
{
    return [
        'id' => Yii::t('backend', 'ID'),
        'first_name' => Yii::t('backend', 'First Name'),
        'last_name' => Yii::t('backend', 'Last Name'),
        'user_id' => Yii::t('backend', 'User ID'),
        'student_number' => Yii::t('backend', 'Student Number'),
        'national_id' => Yii::t('backend', 'National ID'),
        'average' => Yii::t('backend', 'Average'),
        'vip' => Yii::t('backend', 'Vip'),
        'location_id' => Yii::t('backend', 'Location ID'),
    ];
}
public function SaveTextArea()
{
    $users = explode(";", $this->first_name);
    foreach ($users as $user){
        list($first_name,$last_name,$student_number,$national_id) = explode(";", $user);
    }
    return $ali;
}

【问题讨论】:

  • 能否请您发布您的代码的详细信息,以便人们可以帮助您?

标签: activerecord yii2


【解决方案1】:

是的,你可以,只需在你的模型类中添加一个公共属性:

class MyClass extends \yii\db\ActiveRecord
{
    public $myAttribute;
    ...

您还需要将其声明为安全属性,并且它是您的规则方法中的类型:

public function rules()
{
    ...
    [['myAttribute'], 'safe'],
    ...

然后您可以使用其他规则进行任何处理:

public function rules()
{
    ...
    [['myAttribute'], 'safe'],
    [['myAttribute'], 'myCustomFunction'],
    ...
}

public function myCustomFunction($attribute, $params)
{
    // Do explode and assign attribute values here
}

【讨论】:

    【解决方案2】:

    更简单的方法是使用

    \yii\helpers\Html::textarea('the_name_you_need', 'value', options)
    

    这样您就不必使用 ActiveRecord 属性

    你可以阅读它here

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2015-04-08
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多