dongyun6003
2018-11-16 09:36
浏览 163
已采纳

Kartik Select2返回null

i have a problem with Kartik Select2. When I want save multiple data in my controller, nothing is saved. And I remove foreach in controller, Yii return me error with information about $university_id IS NULL.

User Form

<?= $form->field($user_university, 'university_id')->widget(Select2::classname(),[
    'name' => 'university_id[]',
    'data' => ArrayHelper::map(
        \app\models\University::find()->asArray()->all(),
        'id',
        function ($university) {
            return $university['name'];
        }
    ),
    'size' => Select2::MEDIUM,
    'options' => ['placeholder' => 'Select a state ...', 'multiple' => true],
    'pluginOptions' => [
        'allowClear' => true
    ],
]); ?>

User Controller

 $user = new User();
    $user->scenario = User::SCENARIO_CREATE;
    $auth_assignment = new AuthAssignment();
    $user_company = new UserCompany();
    $user_university = new UserUniversity();
    $user_status = UserStatus::find()
        ->select('id')
        ->where(['name' => UserStatus::NON_AUTHORIZED_USER])
        ->one();

    if ($user->load(Yii::$app->request->post()) && $auth_assignment->load(Yii::$app->request->post())) {

        $user->auth_key = Yii::$app->getSecurity()->generateRandomString();
        $user->password_hash = Yii::$app->getSecurity()->generatePasswordHash($user->password);
        $user->password_reset_token = Yii::$app->getSecurity()->generateRandomString();
        $user->status_id = $user_status->id;
        $user->created_at = date('Y-m-d H:i:s');
        $user->updated_at = date('Y-m-d H:i:s');


        if ($user->save()) {
            $auth_assignment->user_id = $user->id;
            $auth_assignment->created_at = date('Y-m-d H:i:s');

            $universities = $user_university->university_id;
            foreach((array) $universities as $university)
            {
                $newUserUniversity = new UserUniversity();
                $newUserUniversity->user_id = $user->id;
                $newUserUniversity->university_id = $university;
                $newUserUniversity->created_at = date('Y-m-d H:i:s');
                $newUserUniversity->save(false);

            }...

User University Model Rule

public function rules()
{
    return [
        [['user_id', 'university_id', 'created_at'], 'required'],
        [['user_id', 'university_id','confirm'], 'integer'],
        [['created_at','university_id'], 'safe'],
        [['university_id'], 'exist', 'skipOnError' => true, 'targetClass' => University::className(), 'targetAttribute' => ['university_id' => 'id']],
        [['user_id'], 'exist', 'skipOnError' => true, 'targetClass' => User::className(), 'targetAttribute' => ['user_id' => 'id']],
    ];
}
  • 写回答
  • 好问题 提建议
  • 关注问题
  • 收藏
  • 邀请回答

2条回答 默认 最新

  • dougu3988 2018-11-16 11:56
    已采纳

    Looking at your code i can't see where you are loading the data from the post request into the $user_university before you start looping on the university_id. You need to call $user_university->load(Yii::$app->request->post()), look the following piece of code from your script

    if ($user->save()) {
       $auth_assignment->user_id = $user->id;
       $auth_assignment->created_at = date('Y-m-d H:i:s');
    
       // this below line will give you an empty string rather than 
       // the selected ids of the `university` that you selected 
       // in the multi-dropdown
    
       $universities = $user_university->university_id;  
    

    and the very next line is the foreach((array) $universities as $university) in which you are trying to save which won't run even once, as there isnt any array loaded in the $unversities. So you can add a call before you get the array from the attribute, dont know if your requirements are to return the user with an error if the data is not loaded for the $user_university otherwise you need to add it to the main check

    if ($user->load(Yii::$app->request->post()) && $auth_assignment->load(Yii::$app->request->post()) &&
    $user->university->load(Yii::$app->request->post())) {
    

    So your code should look like below

    $user = new User();
    $user->scenario = User::SCENARIO_CREATE;
    $auth_assignment = new AuthAssignment();
    $user_company = new UserCompany();
    $user_university = new UserUniversity();
    $user_status = UserStatus::find()
        ->select('id')
        ->where(['name' => UserStatus::NON_AUTHORIZED_USER])
        ->one();
    
    //validate all models
    $allModelsValid=$user->load(Yii::$app->request->post()) && $auth_assignment->load(Yii::$app->request->post()) && $user_university->load(Yii::$app->request->post());
    
    if ($allModelsValid) {
    
        $user->auth_key = Yii::$app->getSecurity()->generateRandomString();
        $user->password_hash = Yii::$app->getSecurity()->generatePasswordHash($user->password);
        $user->password_reset_token = Yii::$app->getSecurity()->generateRandomString();
        $user->status_id = $user_status->id;
        $user->created_at = date('Y-m-d H:i:s');
        $user->updated_at = date('Y-m-d H:i:s');
    
    
        if ($user->save()) {
            $auth_assignment->user_id = $user->id;
            $auth_assignment->created_at = date('Y-m-d H:i:s');
    
            $universities = $user_university->university_id;
            foreach((array) $universities as $university)
            {
                $newUserUniversity = new UserUniversity();
                $newUserUniversity->user_id = $user->id;
                $newUserUniversity->university_id = $university;
                $newUserUniversity->created_at = date('Y-m-d H:i:s');
                $newUserUniversity->save(false);
    
            }...
    

    Also apart from above i dont find a reason to use the name as university_id[] for the dropdown rather than university_id

    已采纳该答案
    评论
    解决 无用
    打赏 举报
  • drgwsx8405 2018-11-16 10:13

    There are multiple ways of Usage of select2 now currently you are using Usage with ActiveForm and model see below multiple ways.

    use kartik\select2\Select2
    
    // Usage with ActiveForm and model
    echo $form->field($model, 'state_1')->widget(Select2::classname(), [
        'data' => $data,
        'options' => ['placeholder' => 'Select a state ...'],
        'pluginOptions' => [
            'allowClear' => true
        ],
    ]);
    
    // With a model and without ActiveForm
    echo Select2::widget([
        'model' => $model,
        'attribute' => 'state_2',
        'data' => $data,
        'options' => ['placeholder' => 'Select a state ...'],
        'pluginOptions' => [
            'allowClear' => true
        ],
    ]);
    
    // Without model and implementing a multiple select
    echo '<label class="control-label">Provinces</label>';
    echo Select2::widget([
        'name' => 'state_10',
        'data' => $data,
        'options' => [
            'placeholder' => 'Select provinces ...',
            'multiple' => true
        ],
    ]);
    
    // A disabled select2 list input
    echo '<label class="control-label">State</label>';
    echo Select2::widget([
        'name' => 'state_11',
        'data' => $data,
        'disabled' => true
    ]);
    

    I guess your problem is in :

    'data' => ArrayHelper::map(
            \app\models\University::find()->asArray()->all(),
            'id',
            function ($university) {
                return $university['name'];
            }
        ),
    

    Please check data attribute .. check you are passing correct array or not.

    评论
    解决 无用
    打赏 举报

相关推荐 更多相似问题