Yii2: set text field's value when an item from a dropdownlist is selected - yii

I have the following code on my form:
<?php
$unitPrices = ArrayHelper::map(Item::find()->where('isApproved and
vendor_id=:id', [':id' => $vendorId])->all(),'id','unitPrice');
?>
this gives me a map called unitPrices where the key-value pairing is id-unitPrice
<?= $form->field($model, 'item_id')->dropDownList(
ArrayHelper::map(Item::find()->where('isApproved and vendor_id=:id', [':id' => $vendorId])->all(),'id','itemCode','description'),
[
'prompt'=>'--Select Item--',
'id'=>'item_selected',
'onchange' => '$("#priceOnLine").val($unitPrices[item_id_value]);',
])
?>
what I want to do is when an item is selected from the dropdownlist, it also sets the value of a text field called priceOnLine using the unitPrices map where the id is the value of the selected item from the dropdownlist.
I tried setting the text field to a static value (100), and it works but I can't figure out how to set it using the map.
'onchange' => '$("#priceOnLine").val(100);',
Thanks in advance for the help :D

You need to get the text of the selected option you can add the following script on the top of your view and remove the 'onchange' => '$("#priceOnLine").val($unitPrices[item_id_value]);', from your dropDown()
<?php
$js=<<<JS
$("#item_selected").on("change",function(){
$("#priceOnLine").val(($(this).find("option:selected").text()));
});
JS;
$this->registerJs($js,\yii\web\View::POS_READY);
Hope it helps

Related

Show fa icon inside Chtml::link() in Yii1

Im using CHtml::link() for attachment in my grid view and if i click on it, it will open in new tab to display.
My doubt is how can i use font awesome icon to display attachment in grid. Currently it showing from table but i want to display <i class="fa fa-paperclip" aria-hidden="true"></i> this icon for that column.
array(
'name' => 'invoice_attachment',
'value' => 'CHtml::link($data->invoice_attachment, Yii::app()->request->baseUrl.$data->invoice_attachment, array("target"=>"_blank"))',
'type' => 'raw',
),
The above code is my current output for link.
CHtml::link($text, $url, $htmlOptions) method accepts 3 parameters:
$text - this is what you want, right now youre setting here $data->invoice_attachment (propably file name) - change this to your <i> string
$url - a URL or an action route that can be used to create a URL
$htmlOptions - additional HTML attributes
Change $text param and that's all.

Remove red * in required fields Yiibooster

I'm using yiibooster and it is really good extension for the frontend, my issues now is that I want to remove the red * that is rendered in the required fields but maintaining the required validator in the model, anyone knows how to do this????
thankss
This is an example of a label generated by a required field validator:
<label for="User_email" class="required">
Email Address <span class="required">*</span>
</label>
Therefore, you can hide it by adding this class to your site's CSS:
span.required {
display: none;
}
If you want to achieve what you want easily, I suggest you to do like below, which is simplest way(in my view point):
Just try to find * selector(the ID or CLASS) name.(using a firebug or any inspector)
Then just do like below in your document.ready():
$(SELECTOR).remove();
NOTES
THE * MIGHT BE CREATED DYNAMICALLY
THIS IS JUST AN SUGGESTION, YOU CAN FIND ANY OTHER POSSIBLE WAYS SUCH AS CHANGING THE CSS CLASS IN ORDER TO DO DISPLAY:NONE OR SOURCE MODIFICATION
<?php echo $form->textFieldGroup($model, 'username',array('label'=>Yii::t('model','Username'))); ?>
or edit line 1223 of TbActiveForm.php from
echo $this->labelEx($model, $attribute, $options['labelOptions']);
to
echo $this->label($model, $attribute, $options['labelOptions']);
Red * is adding according to your validators definition in your model. you have two options.
First in your model add On => 'scenario name' for required validator for the property you want. so you can control the behavior of yii-booster components because they only apply those rules which matches the scenario of the model. for example:
array('password_repeat', 'required', 'on'=>'register'),
It will show Red * only in register scenario (if you set it via $model->setScenario('register');) and in normal times no red * will shown.
Another option for you is when you are creating the form element based on the property marked required by validator rules in model, you can prevent that * from showing but this way will not ignore that validation rule and if you try to submit the form while this form field is empty you will get error from yii (because you just solve showing but in background you have your required validator). for this method, you only need to provide label in your yii-booster form element:
<?php echo $form->textFieldGroup($model,'textField',
array(
'wrapperHtmlOptions' => array(
'class' => 'col-sm-5',
),
'hint' => 'In addition to freeform text, any HTML5 text-based input appears like so.',
>>>>> 'label' => 'Your new value for label which will have no red *',
)
); ?>

Is it possible to have the same Model and CGrid parameter in a form

I have a form
$form=$this->beginWidget('CActiveForm', array('id'=>'subject-form','enableAjaxValidation'=>false,));
which has a parameter "Subject"
$form->labelEx($model,'subject');
$form->textField($model,'subject',array('size'=>200,'maxlength'=>255));
I would also like to add a "Subject Search Grid" further down the view (so I can search other Subjects as I'm editing the current). To that end I am passing $model into the view as normal, plus an alias $relatives to the grid.
$subject_search_grid= $this->widget(
'zii.widgets.grid.CGridView',
array(
'id'=>'subject-grid',
'dataProvider'=>$relatives->search(),
'filter'=>$relatives,
'columns'=>array(
'id',
'subject',
array('class'=>'CButtonColumn',),
),
),
$captureOutput=true
);
CGrid is working perfectly, however it's instance of 'subject' is overwriting the $form 'subject' when I try save or update the form. Is there any way of moving CGrid out of the view logic so it does not overwrite the value?
thanks
Place the gridview outside the form? So after <?php $this->endWidget(); ?>.

How to implement a dynamic js script in Yii List View?

Hello and thanks for reading my question. I have a typical list view:
<?php $this->widget('bootstrap.widgets.TbListView',array(
'dataProvider'=>$dataProvider,
'itemView'=>'_view',
'emptyText'=>'No Jobs',
)); ?>
In my _view file I have a div and a button that slideToggles the div. If I just put the Javascript at the top of the page, it does not work because the results are dynamic and the name of the div changes with the id returned, eg:
id="detailsDiv-<?php echo $data->id_employer_contract;?>"
The problem is in my Javascript, which is as follows:
<?php Yii::app()->clientScript->registerScript('details', "$('#details-$data-id_employer_contract').click(function(){
$('#detailsDiv-$data->id_employer_contract').slideToggle();
return false;});");?>
How can I make this Javascript code dynamic? Meaning, how can I loop through the id? I tried adding the code to the listview property ajaxUpdate but it's still not working. Can someone tell me how I can loop a Javascript in a list view?
Add the id to your toggle buttons as data attribute:
<button class="toggleDetails" data-id="<?php echo $data->id_employer_contract ?>">
Then you can access these data attributes like this js:
<?php Yii::app()->clientScript->registerScript('toggleDetails', "
$('.toggleDetails').click(function(e){
var id = $(this).data('id');
$('#detailsDiv-' + id).slideToggle();
e.preventDefault();
});
", CClientScript::POS_READY) ?>
NOTE: You should not put this javascript into _view.php but into the main file where you render the List View. You only need this one single snippet to deal with all your buttons.

Saving a checkbox value in Yii

I can't figure out how to properly save checkbox values in Yii. I have a MySQL column, active, defined as a tinyint. I have the following form creation code, which correctly shows the checkbox as checked if the value is 1 and unchecked if 0:
<?php echo $form->labelEx($model,'active'); ?>
<?php echo $form->checkBox($model,'active'); ?>
<?php echo $form->error($model,'active'); ?>
And the code to save the form correctly changes other, text-based values:
public function actionUpdate($id)
{
$model=$this->loadModel($id);
if(isset($_POST['Thing']))
{
$model->attributes=$_POST['Thing'];
if($model->save())
$this->redirect(array('thing/index'));
}
$this->render('update',array(
'model'=>$model,
));
}
The value of active is not saved. Where am I going wrong?
You can use htmlOptions array to specify value attribute. Below is the code example:
<?php echo $form->labelEx($model,'active'); ?>
<?php echo $form->checkBox($model,'active', array('value'=>1, 'uncheckValue'=>0)); ?>
<?php echo $form->error($model,'active'); ?>
Since version 1.0.2, a special option named 'uncheckValue' is
available that can be used to specify the value returned when the
checkbox is not checked. By default, this value is '0'.
(This text is taken from YII Documenration)
For every input that you are accepting from user, you need to define it in model::rule(). is active defined there in rule()?
In general, if you are having problems saving to the database, i would replace
$model->save();
with
if($model->save() == false) var_dump($model->errors);
that way, you can see exactly why it did not save. it is usually a validation error.
Please follow:
1. in protected/models/Thing.php add active as a numeric
public function rules()
{
// NOTE: you should only define rules for those attributes that
// will receive user inputs.
return array(
array('active', 'numerical', 'integerOnly'=>true),
//OR optional
array('active', 'safe'),
);
}
Controller action: Its ok
View:
<?php echo $form->labelEx($model,'active'); ?>
<?php echo $form->checkBox($model,'active', array('value'=>1, 'uncheckValue'=>0)); ?>
<?php echo $form->error($model,'active'); ?>
Hope this will work for you...
Article which can be helpful when figuring out how to handle booleans & checkboxes in Yii
http://www.larryullman.com/2010/07/25/handling-checkboxes-in-yii-with-non-boolean-values/
I used a bit type field in my DB and it didn't work.
1.- I changed the field type to tinyint
2.- In the rules function added:
array('active','numerical'),
3.-In the form (as D3K said) do:
<?echo $form->checkBox($model,'active',array('value'=>1, 'uncheckValue'=>0));?>
You can check by printing all the attributes which are being captured. If active is not captured, it must not be safe. you need to declare the variable as safe or define a rule around that variable. This will make the variable safe.
I have similar the same problemce before,I change data type is int,so it save
We can also add a rule as safe in model to pass the values from form to controller without missing.
array('active', 'safe'),
well this post is so old but I've found a solution very useful specially for giving checkbox a value specified rather than number. The new syntax is something like this
notice I'm using ActiveForm
field($model3, 'External_Catering')->checkbox(['id' => 'remember-me-ver', 'custom' => true,'value'=>"External_Catering", 'uncheckValue'=>"vide"]) ?>
1) where my model is =>model3
2) with the name External_Catering
3) that take the value External_Catering and empty when it's uncheckValue
4) in Controller you get the value just by specifying the model and it's attribute like
  $External_Catering=$model3->External_Catering.