2017-04-25 27 views
0

我使用以下的(簡單)的代碼與在yii2的形式來使用的模型:Yii2:模型不加載陣列

class ChooseAgeCategoriesForm extends Model 
{ 

    public $ageCategories; 

    /** 
    * @return array the validation rules. 
    */ 
    public function rules() 
    { 
     return [ 
      ['ageCategories', 'safe'], 
      [['ageCategories'], 'each', 'rule' => ['integer']], 
     ]; 
    } 
} 

然而,然後試圖加載模型是這樣的:

$model = new ChooseAgeCategoriesForm(); 

if ($model->load(Yii::$app->request->post())) { 
     $acIDs = $model->ageCategories; 
} 

該代碼從未執行。實際上,$model->load返回Bool(false),但$model->errors爲空。傾銷post內容產生這樣的結果:

array(2) { ["_csrf"]=> string(56) "SzhjdWIuc0oIQSA0BEs4BDp8KzYEXwM5CG80RhNBRDkPUzIXO1gBew==" ["ageCategories"]=> array(9) { [0]=> string(1) "1" [1]=> string(1) "2" [2]=> string(1) "3" [3]=> string(1) "4" [4]=> string(1) "5" [5]=> string(1) "6" [6]=> string(1) "7" [7]=> string(1) "9" [8]=> string(2) "10" } } 

所以,是的,現場實際發送和填充的數字陣列。我在這裏看不到什麼問題?提前致謝。我也嘗試添加['ageCategories', 'exist', 'allowArray' => true],作爲另一個規則,但這也不起作用。有任何想法嗎?

表單代碼

按照要求,形式本身的代碼:

<?php $form = ActiveForm::begin([ 
    'action' => Url::to(['/result/team-result']), 
    'method' => 'post', 
    'options' => ['id' => 'chooseAgeCategory', 'style' => "margin-bottom: 15px;"] 
]); ?> 

<?= Select2::widget([ 
    'name' => 'ageCategories', 
    'id' => 'ac-id', 
    'value' => $acIDs, 
    'data' => ArrayHelper::map(AgeCategory::find()->all(), 'id', 'name'), 
    'options' => ['multiple' => true, 'placeholder' => Yii::t('view', 'Select Age Category')], 
    'pluginEvents' => [ 
     "change" => "function() { this.form.submit(); }", 
    ] 
]) ?> 

<?php $form->end(); ?> 
+0

顯示你的窗體的代碼添加 – gmc

+0

窗體的代碼的問題。 –

+0

什麼是變量'$ model'的類? – gmc

回答

1

請像下面那樣更改您的select2小部件代碼。與字段名稱一樣

ChooseAgeCategoriesForm [ageCategories]

如果你檢查你的表格你會知道Yii2包裝型號名稱。所以你必須在select2部件中給出模型值。

<?= Select2::widget([ 
    'model' => $model, 
    'attribute' => 'ageCategories', 
    'id' => 'ac-id', 
    'value' => $acIDs, 
    'data' => ArrayHelper::map(AgeCategory::find()->all(), 'id', 'name'), 
    'options' => ['multiple' => true, 'placeholder' => Yii::t('view', 'Select Age Category')], 
    'pluginEvents' => [ 
     "change" => "function() { this.form.submit(); }", 
    ] 
]) ?> 

編號:http://demos.krajee.com/widget-details/select2

+0

添加「屬性」元素有訣竅。謝謝。 –

1

我會建議你使用使用model屬性Select2,這樣就會自動鏈接到現場簡化加載過程,並使用您的模型驗證功能:

<?= Select2::widget([ 
    'name' => 'ageCategories', 
    'id' => 'ac-id', 
    'value' => $acIDs, 
    'data' => ArrayHelper::map(AgeCategory::find()->all(), 'id', 'name'), 
    'options' => ['multiple' => true, 'placeholder' => Yii::t('view', 'Select Age Category')], 
    'pluginEvents' => [ 
     "change" => "function() { this.form.submit(); }", 
    ] 
]) ?>