Removing a field from a form generated by YII2 ActiveForm - php

I have a form generated using YII2 ActiveForm. there are some field I need to be on the if I select certain options , or need to have them removed if I select some other option.
For e.g. I Have a dropdown AccountType, with two options "individual" and "company".
If the user selects "individual" some fields on the form needs to go away say company name, and some other fields need to appear such as First name, last name. Initially when the display the form , only the Account Type field is there.
below is the code I have at the moment
<?php
$form = ActiveForm::begin(['id' => 'account-setup-form']); ?>
echo $form->field($modelAccMain, 'account_type')
->widget(Select2::classname(), [
'data' => $accountTypeArray,
'options' => ['placeholder' => 'Select account type'],
]);
echo $form->field($modelUsers, 'firstname')->textInput()
->hint('')->label('First Name');
echo $form->field($modelUsers, 'lastname')->textInput()
->hint('')->label('Last Name');
<?php ActiveForm::end(); ?>
Any help is greatly appreciated.

You can use scenarios for that, first define them in your model and than you can use a if statement in your view
if ($model->isAttributeActive('attribute_name')) {
But like #nterms wrote, if you want the user to be able to switch on the client side, javascript would be better.
Defining scenarios also helps with the validation (only active attributes will be validated).
p.s. Don't forget to set the scenario in your controller
$model = new MyModel(['scenario'=>'my_scenario']);

The way i would handle it is with jquery hide and show using the change event of the dropdown,
In your javascript
Assuming that the data in the select 2 widget is in the form of array
eg:
[1=>"first-item",2=>"second-item",...]
$(document).ready(function(){
var id= //check the id of the select2
on the inspect element id using chrome;
$("#id").on("change", function(){
if(id.value==1){
//show a div
}else{
//hide a div
}
//for multiple values better use switch
like this
switch(id){
case 1:{
$("#divid").show();
......
}
}
})
})
I hope you get the idea,
For the select 2 id you can set it via
echo $form->field($modelAccMain, 'account_type')
->widget(Select2::classname(), [
'data' => $accountTypeArray,
'options' => ['placeholder' => 'Select account type',"id"=>"mypreffereid"],
]);

Related

Symfony6 - add iput field after submitting form

i have an ChoiceType::class input field in my form with, now just as an example, two choices:
'choices' => ['type1' => '1', 'type2' => '2']
now when the user select type2 i want to add an exta TextType::class inputfield to the form.
But i dont want to show the input field before and i want it to be required if selected type2 and not if selected type1.
I hope it make sense, i try it to to with javascript and set the attribute to hidden or not, but
then the form is not been send because of the required attribute.
I tried it with form events but did not get it to work in that way.
Thanks
You were on the right way, you have to do it in Javascript. You just need to manage the attr required in Javascript so that the form does not block you with something like this:
Remove the required attribute from a field: document.getElementById("id").required = false;
Make a field required : document.getElementById("id").required = true;
And you can check if the form can be sumitted with : document.getElementById("idForm").reportValidity();.
I using implementation of conditional fields with data-attributes, e.g.:
->add('typeField', EnumType::class, [
'label' => 'Type',
'class' => MyTypeEnum::Class,
])
->add('someField', TextField::class, [
'data-controller' => 'depends-on',
'data-depends-on' => 'my_form_typeField',
'data-depends-value' => MyTypeEnum::OTHER->value,
])
On frontend JS stimulus controller show/hide someField depend on typeField value.
And validation() function in object ('data_class' in formType) make custom validation, e.g.:
/**
* #Assert\Callback
*/
public function validate(ExecutionContextInterface $context)
{
if ($this->typeField !== MyTypeEnum::OTHER) {
$context->buildViolation('message')->atPath('typeField')->addViolation();
}
}

how to get and display username in another form field when user select name from dropdownlist in yii2?

I want to display the lecturer username in another text input field form when the user selects the lecturer name in the drop-down list above.
this is my code for drop-down list lecturer name
<?= $form->field($model, 'LecturerName')->dropDownList(
ArrayHelper::map(User::findAll(['category' => 'lecturer']),'fullname','fullname'),
['prompt'=>'Select Lecturer']
) ?>
this is my code for lecturer username
<?= $form->field($model, 'LecUsername')->textInput(['maxlength' => true]); ?>
I want to get and display the LecUsername based on the selected drop-down list above. the LecUsername is from the database.
As you are using the dropdown you need to bind the change event for the dropdown to insert the value from the dropdown to the input text. And to make sure that you are inserting the LecUsername for the LecturerName you need to have the LecUsername as the value for the dropdown, means the drop-down data should have the username field as the index, currently you are using the fullname as the index and the value so change the code according to the field name you have for the username, i assume it is username for the example.
ArrayHelper::map(User::findAll(['category' => 'lecturer']),'username','fullname')
so your dropdown code will look like
<?= $form->field($model, 'LecturerName')->dropDownList(
ArrayHelper::map(User::findAll(['category' => 'lecturer']),'username','fullname'),
['prompt'=>'Select Lecturer']
) ?>
then add the below on top of your view file where you have the form
$ddId=Html::getInputId($model, 'LecturerName');
$inputId=Html::getInputId($model, 'LecUsername');
$js = <<< JS
$(document).ready(function(){
$("#{$ddId}").on('change',function(e){
$("#{$inputId}").val($(this).val());
});
});
JS;
$this->registerJs($js, \yii\web\View::POS_READY);
A better way for dropdowns is to use the library Kartik-v\select2 and use the event pluginEvents option to specify the event select2:select, your code should look like below in that case.
// Usage with ActiveForm and model
echo $form->field($model, 'LecturerName')->widget(Select2::classname(), [
'data' => ArrayHelper::map(User::findAll(['category' => 'lecturer']),'username','fullname'),
'options' => ['placeholder' => 'Select Lecturer'],
'pluginOptions' => [
'allowClear' => true
],
'pluginEvents'=>[
"select2:select" => 'function() { $("#{$ddId}").on('change',function(e){
$("#{$inputId}").val($(this).val());
}); }',
]
]);

Adding some more fields to the form in yii2 using ajax

I have a Yii2 form:
<?php $form = ActiveForm::begin(['id' => 'que']); ?>
<?php echo $form->field($model, 'type')
->dropDownList($questionTypes, [
'class' => 'form-control ng-pristine ng-valid ng-touched',
'prompt' => 'Select question type',
'ng-model' => 'que.type',
'ng-change' => 'addAnswerOptions(que);',
]);
?>
<?php ActiveForm::end(); ?>
On the basis of selected dropdown value, I have to add some more fields to the same form of the same model. What fields will be added, is totally depend on the dropdown value.
How can I do this?
From the information you give out here is what I would suggest.
1) Dynamic - no AJAX
Build your form with all the fields you need, just contain each "scenario" in a separate div like follows:
<?php $form = ActiveForm::begin(['id' => 'que']); ?>
<?php echo $form->field($model, 'type')
->dropDownList($questionTypes, [
'class' => 'form-control ng-pristine ng-valid ng-touched',
'prompt' => 'Select question type',
'ng-model' => 'que.type',
'ng-change' => 'addAnswerOptions(que);',
]);
?>
<div class="form-option" data-type="class" style="display:none;">
<?php
// ... fields here for case type == class
?>
</div>
<div class="form-option" data-type="prompt" style="display:none;">
<?php
// ... fields here for case type == prompt
?>
</div>
<div class="form-option" data-type="ng-model" style="display:none;">
<?php
// ... fields here for case type == ng-model
?>
</div>
<div class="form-option" data-type="ng-change" style="display:none;">
<?php
// ... fields here for case type == ng-change
?>
</div>
<?php ActiveForm::end(); ?>
Then you will want to register Javascript code to display the correct blocs depending on which dropdown option was selected.
Bellow is an example using JQuery:
$(document).ready(function(){
$('select.form-control').change(function(){
$('.form-option').hide(); // hide all options if an option is showing
var index = $('select.form-control').index();
$('div[data-type="'+index+'"]').show(); //show the correct fields
});
});
If you're going to go this way I suggest you use AJAX validation for your form. It will avoid you having to deal with a headache on page reload.
Once your form is submitted you will have to handle each case in your controller. You can either use a simple set of if() statements that check the drop down value. Or you can set your model validation scenario according to the drop down value.
The advantage of this is that it will be quicker and you will be able to take advantage of ActiveForm. the cons are that you need to know which fields you want to display for each option, and it doesn't allow you to cumulate n number of fields when you don't know how much n is.
2) Using Ajax
In the event that you want to use ajax calls to load the extra form fields you will have to make a controller/action combination that will return the fields depending on the type that you pass in the GET
This action will generate the html of the fields you want to display. Here's an example:
public function actionAjaxFields($type)
{
$html = '';
if($type == "class")
{
$html .= Html::textInput('Field1');
}
elseif($type == "prompt")
{
$html .= Html::textInput('Field2');
}
else
{
// etc...
}
return $html;
}
Note that you can also pass a user id to this method which will allow you to generate a model and use Html::activeTextInput(), however you will not be able to take advantage of ActiveForm features.
Once this is done, you should bind a function to the change event of the dropdown and use something along the lines of :
var responsePromise = $http.get("controller/ajax-fields", {params: {type: <type-from-dropdown>}});
Unfortunately I do not know much about angularjs so this is the extent of the help I can give on the javascript side of things. I'm sure there's more than enough information on google/stackoverflow about binding events and appending data to the DOM in angularjs to get you running.
Let me know if I can be of any extra help on the Yii2 side.

Yii CGridView - Custom Columns

been looking for a solution to add a feature for "Custom Columns"... Meaning, I present a list of columns that I can show the user and he selects the ones he wants to see and after the selection the table is updated and add/removes the needed columns.
Didn't find anything on Google (perhaps it has a different name than what I was looking for...)
Anyone has an Idea on how it can be accomplished?
Thanks in advance!
This is not a complete sample, but can give you some clues on how to implement it. You've to define some kind of form to collect the data about how your grid has to be rendered. I recommend you to create a CFormModel class if there are more than 3 input fields. Create a view file with the form and a div or renderPartial of a file containing a grid:
$form = $this->beginWidget('CActiveFormExt');
echo $form->errorSummary($model);
echo $form->labelEx($model,'column1');
echo $form->dropDownList($model
echo $form->error($model,'column1');
echo CHtml::ajaxSubmitButton('UpdateGrid',array('controller/grid'),
array('update'=>'#grid'),
$this->endWidget();
// you can render the 'default options' before any ajax update
$this->renderPartial('_grid',array($customColumns=>array('id','name'),'dataProvider'=>$dataProvider));
In the _grid.php view file:
$this->widget('zii.widgets.grid.CGridView', array(
'id' => 'grid',
'dataProvider'=>$dataProvider,
'columns' => $customColumns;
));
In the controller:
function actionGrid(){
// recover the form data, and build the custom columns array
$customColumns = array();
$customColumns[] = '.....';
$dataProvider = ...;
$this->renderPartial('_formTrabajo', array('customColumns' => $idSiniestro, 'dataProvider' => $dataProvider'), false);
}
When you click the ajaxSubmitButton, the form is sent to the url specified through ajax, and the reply from the controller must contain the renderPartial of the view containing the grid, so the jQuery call can replace the html correctly. You must pass an array from your controller to the partial view of the grid, with the custom list of columns you want to display.

CakePHP Form Helper: Select helper is not defaulting certain custom fields

I am having a problem with the form select helper. On my page I have two forms.
One is a quick search form. This one uses state_id.
Upon searching in URL: state_id:CO
This will auto select the correct value in the drop down.
However, when I search with the advanced form. The Field is trail_state_id and
in URL: trail_state_id:CO
For some reason it will not default it to the correct value. It just resets the form to no selections. The values are searhed properly, just the form helper is not recognizing that a field with the same name in the url is set. Any thoughts?
<?php
class Trail extends AppModel {
public $filterArgs = array(
array('name' => 'state_id','field'=>'Area.state_id', 'type' => 'value'),
array('name'=>'trail_state_id','field'=>'Area.state_id','type'=> 'value'),
);
}
?>
in URL: trail_state_id:CO
<?php
echo '<h4>State*:</h4><div>'.$this->Form->select('trail_state_id', $stateSelectList, null, array('style'=>'width:200px;','escape' => false,'class'=> 'enhanced required','empty'=> false));
?>
Using the 3rd argument in the helper you can set a default. I did it the following way;
echo '<h4>State*:</h4><div>'.$this->Form->select('trail_state_id', $stateSelectList, (empty($this->params['named']['trail_state_id']) ? null: $this->params['named']['trail_state_id']), array('style'=>'width:200px;','escape' => false,'class'=> 'enhanced required','empty'=> false));

Categories