Yii2 how to create table template using select2 widget - php

I have a dropdown list using select2 widget to get the customer contact
$getcontact = ArrayHelper::map(OpContact::find()->all(),'id','code');
<div class="col-md-10">'.
$form->field($model, 'contact_id')->widget(Select2::classname(), [
'data' => $getcontact,
'language' => 'en',
'options' => ['placeholder' => 'Select'],
'pluginOptions' => [
'allowClear' => true
],
])->label(false).'
For now, its just a normal dropdownlist which show only the contact id.How I can like insert 2nd column for it and put all the data inside a table. For example, I want the dropdown to look like this where I can see the id and the contact name together.
------------------------------
ID Contact ID
------------------------------
21 contact1
22 contact2
23 contact3
24 contact1
Anyone have any idea? Thanks

if you want store only the id and see both id and contactID and contact ID is th concat of id and code you couuld use
$getcontact = ArrayHelper::map(OpContact::find()
->select('id, concat(id, code) as contactID')
->all(),'id','contactID');
if you want store both you can
$getcontact = ArrayHelper::map(OpContact::find()
->select('concat(id, code) as id, concat(id, code) as contactID')
->all(),'id','contactID');

you can't show all of them , but you can merge that field in string mode in your query like CONCAT or in your foreach merge string with " . " together

Change ArrayHelper as below .
$getcontact = ArrayHelper::map(OpContact::find()->all(),'id',function($model){ return $model->id.'-'.$model->code; });

Related

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());
}); }',
]
]);

Saving another field value instead of id in drop down in yii 1

I have following code in my view
<?php echo $form->dropDownList($model,'p_28',
CHtml::listData(AdCourt::model()->findAll(),'id','name') ,
array(
'class'=>'form-control',
'style'=>'width:100%;',
'empty'=>Yii::t('plaint','Суд турини танланг'),
'ajax' => array(
'type'=>'POST', //request type
'url'=>$this->createUrl('getcourts'),
'update'=>'#ABlockForm_p_29',
)
)); ?>
AdCourt takes values from ad_court table. This tables consists of id, name and court_id. I need to save database court_id instead of id.
How can I do it?
The second parameter of listData is the attribute of the items that will be used as the value for the <option> tag. As such to use the court_id instead of the id you should pass it instead:
CHtml::listData(AdCourt::model()->findAll(),'court_id','name')

Removing a field from a form generated by YII2 ActiveForm

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"],
]);

SF 1.4 How to make a form with several checkboxes and a relation between 2 models

Good morning,
In Symfony 1.4, I have two models, as in the following example :
ModelA
id
text
.
ModelB
id
name
modele_a_id
I want to create a form with checkboxes for each ModeleB entries, and a textarea for the text of ModeleA, like that :
[] modele_b_entry_name_1
[] modele_b_entry_name_2
[] modele_b_entry_name_3
text
[_______________________________]
I'm not sure of how to do that.
For the moment I have modified the ModeleAForm which was generated.
Here is the Form code :
$a_id = $this->getObject()->getId();
$query = Doctrine_Query::create()
->from('ModeleB m')
->where('m.modele_a_id = ?', $a_id);
$all_modele_b_entries = $query->execute();
$this->widgetSchema['all_modele_b_entries'] = new sfWidgetFormSelectCheckbox(array('choices' => $all_modele_b_entries));
And the template is very simple, it just shows the form.
I'm getting what I want, except that the labels of the checkboxes are the id of modele_b.
I'm wondering if I should use sfWidgetFormInputCheckbox instead of sfWidgetFormSelectCheckbox and then loop on it.
What do you think of this ? What is the best way to do it for you ?
Thank you in advance for your advices.
Edit :
Trying with the suggestion :
$this->widgetSchema['all_modele_b_entries'] = new sfWidgetFormDoctrineChoice(array(
'model' => 'ModeleB',
'expanded' => true,
'multiple' => true,
'query' => $query ));
I would use sfWidgetFormDoctrineChoice:
$this->widgetSchema['all_modele_b_entries'] = new sfWidgetFormDoctrineChoice(array(
'model' => 'ModelB'
'query' => $query
));
When the widget is rendered it uses the __toString() method of the ModelB class so make sure it's implemented and that it returns what you want. Have a look also on the different option of the choice widget as you can configure a thing or two :)

Select or Dropdown list from CActiveRecord in Yii

I have table types and i want to build selectbox with all values from this table
In my controller i wrote this code
$allRegistrationTypes = RegistrationType::model()->findAll();
$this->render('index', array('allRegistrationTypes' => $allRegistrationTypes))
How build selectbox in view file ?
Well then its pretty simple all you need to do is first create List Data like
CHtml::ListData(allRegistrationTypes,'value you want to pass when item is selected','value you have to display');
for ex
typeList = CHtml::ListData(allRegistrationTypes,'id','type');
now remember both id and type are fields in table
now all you have to do is if you are using form then
<?php echo $form->dropDownList($model, 'type_id', $typeList, array('empty'=>'Select a tyoe')); ?>
and if you need multiple you can pass multiple => multiple in the array as htmlOptions
You would use CHtml::dropDownList, or activeDropDownList if there is a "parent" model and you want to leverage its validation rules.
If you want to make the <select> element multiple-selection-capable, pass in 'multiple' => 'multiple' and 'size' => X as part of the $htmlOptions parameter.
Simplest Method to get "Select Box" in YII Framework:
<div class="row">
<?php
echo $form->labelEx($model,'county');
$data = CHtml::listData(County::model()->findAll(), 'id', 'county');
$htmlOptions = array('size' => '1', 'prompt'=>'-- select county --', );
echo $form->listBox($model,'county', $data, $htmlOptions);
echo $form->error($model,'county');
?>
</div>
Good Luck..

Categories