0

I'm new to Yii framework and I'm designing a form (I'm using create form) to create a row in database. Let me explain about the scenario succintly, so that I can make it clear for what I want-

I have 10 fields in this form. Out of this 10 fields, five fields change dynamically. I created two div's basically div A and div B and repeated the fields as required for the two cases. Say some fields which are textfields in div A will be dropdownlists in div B.

<div id="A">
<?php echo $form->labelEx($model,'selectionList'); ?>
<?php echo $form->textArea($model,'selectionList',array('rows'=>6, 'cols'=>50)); ?>
<?php echo $form->error($model,'selectionList'); ?>
</div>  

<div id="B">
<?php echo $form->labelEx($model,'selectionList'); ?>
<?php echo $form->dropdownList($model,'selectionList',array('rows'=>6, 'cols'=>50)); ?>
<?php echo $form->error($model,'selectionList'); ?>
</div>

I have two radiobuttons say Single and Multi. When I select Single radiobutton, div A should be considered and div B discarded and when I select Multi, vice versa should happen. So, is this the right way to change the form fields dynamically. Or else how can I do this using Ajax validation.

1 Answer 1

1

Not so related to question:

1) You are using same name for all fields, so only last one will be submitted (check generated html, name is MyModel[selectionList] and not MyModel[][selectionList]

2) You will have lots of problems with Ajax validation and dynamic fields (generated via js), since CActiveForm will generate js code via php.

Related to question:

3) To use one or another field, i suggest you to have two separate field names and just hide with js/css one, that is not needed right now. After submitting, just check value of radio button and decide what fields will be saved.

To validate these inputs, you have to use model scenarios (will define in rules what to validate and what not to):

$model = MyModel();
if ($_POST['C'] == 'multi') {
    $model->scenario = 'validateOnlyFirstField';
} else {
    $model->scenario = 'validateOnlySecondField';
}

Also you can use second CActiveForm.validate() parameter to define what attributes to validate.

Sign up to request clarification or add additional context in comments.

3 Comments

Hi @Justinas, I had the same problem, When I tried to submit the form , the fields in second div got overridden over the first radiobutton
Now, I'm thing of appending parameters to the URL and based on parameter I will consider the div. Is it a good practice.
@user3004356 it's same as sending it via _POST. You have to use unique inputs names to send both values.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.