yii2-formwizard изменить модель после выбора select2 - PullRequest
0 голосов
/ 28 января 2020

Я пытаюсь реализовать форму для нескольких моделей, используя виджет form-wizard , с профилем в качестве основной модели и несколькими другими в качестве связанных. Когда я выбираю поле типа сущности для основной модели, я хотел бы изменить связанную модель для следующего шага, основываясь на значении поля типа сущности. Я пытался с этим кодом:

Create Form Code


$modelUrlReletedModelsCreate = Profile::urlRelatedModelCreate();
$urlLinkedProfile = Url::to(['create']);

echo FormWizard::widget([
'formOptions'=>[
    'id'=>'profile_form',
    'enableClientValidation'=>true,
    'enableAjaxValidation'=>true,
    'validationUrl' => Url::to(['profile-models-validation'])

],
'theme' => FormWizard::THEME_MATERIAL_V,
'steps' => [
    //step 1 
    [
        'model' => $model,
        'title' => \Yii::t('app', 'Profile'),
        'fieldConfig' => [
            'only' => ['entity_type_id', 'profile_type_id'], 
            'entity_type_id' => [
                'widget' => Select2::class,
                'options' => [
                    'data' => EntityType::arrayNamesList(),
                    'options' => ['placeholder' => \Yii::t('app','Select an element')],
                    'pluginEvents' => ['select2:select'=>'function(e){;'
                                            . 'var type = $("#pr-ty-sel").val();'
                                            . 'var profile= "'.($model->profile_id ? : "no").'";'
                                            . '$.ajax({ method: "GET",'
                                                    . 'url:"'.$urlLinkedProfile.'",'
                                                    . 'data:{ entity_text : e.params.data.text,'
                                                            . 'entity_id : e.params.data.id,'
                                                            . 'profile_type_id : type,'
                                                            . 'profile_id : profile},'
                                                    . 'success: function(data){'
                                                        . '$("#profile_form").html(data);'
                                                    . '}'
                                                  . '});}'],
                ],

            ],
            'profile_type_id' =>[
                'widget' => Select2::class,
                'options' => [
                    'data' => \app\models\ProfileType::arrayNamesList(),
                    'options' => ['placeholder' => \Yii::t('app','Select an element'),'id'=>'pr-ty-sel'],
                ],

            ]
        ],
        'description' => \Yii::t('app', 'Add Profile Type Data'),
        'formInfoText' => \Yii::t('app', 'Fill all fields'),
    ],

    //step 2 I want ot change here $linkedModel 
    [
        'model' => [$model,$linkedModel],
        'title' => \Yii::t('app', 'Personal Data'),
        'description' => \Yii::t('app', 'Insert Personal Data'),
    ],
]
]);

Controller Action Create Code

public function actionCreate($profileId = NULL)
{

    if($profileId AND $profileId !== 'no'){
        $model = $this->findModel($profileId);
    }else{
        $model = new Profile();
    }

    $profileLinkedModel = new ProfilePrivate();
    $renderMethod = 'render';
    if (Yii::$app->request->isAjax) {
        $entityText = \Yii::$app->request->get('entity_text');
        $entity_id = \Yii::$app->request->get('entity_id');
        $profileTypeId = \Yii::$app->request->get('profile_type_id');
        $profileId = \Yii::$app->request->get('profile_id');

        //Utility function to clean the entity text (remove number and special characters)
        $entityTextCleaned = \app\components\Utility::cleanString($entityText);

        if ($entityTextCleaned == 'private') {
            $profileLinkedModel = new ProfilePrivate();
        } elseif ($entityText == 'company') {
            $profileLinkedModel = new ProfileCompany();
        } else {
            //@TODO 
            return FALSE;
        }

        $model->entity_type_id = $entity_id;
        $model->profile_type_id = $profileTypeId;


        $profileLinkedModel->profile_id = $model->profile_id;
        Yii::$app->response->format = Response::FORMAT_JSON;

        $renderMethod = 'renderAjax';
    }

    //extra table field used to enable custom rule in model
    $model->createFullProfile = TRUE;

    if ($model->load(Yii::$app->request->post())) {
        return $this->redirect(['view', 'id' => $model->profile_id]);
    }

    return $this->$renderMethod('create', [
        'model' => $model,
        'profileLinkedModel' => $profileLinkedModel,
    ]);
}

Когда я выбираю поле для поля типа сущности, сервер запускает запрос ajax на событие выбора, но когда оно заканчивается, другое поле формы не является более выбираемым , Другими словами, после запроса ajax я не могу выбрать поле типа профиля. Если я попытаюсь выбрать поле типа профиля перед полем типа сущности, я могу go перейти к следующему шагу, но всегда загружать модель по умолчанию.

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...