Yii2 preselect radiobutton value - yii2

I know I can use
<?= $form ->field($model, 'subject')
->textInput(array('value' => 'VALUE'))
->label('Titel'); ?>
to prefill a Textfield, but how can I do it for a radioList?
<?= $form ->field($model, 'locations')
->radioList($regionen)
->label('Regionen');
I could use ->textInput again but this transforms the whole List into a single Textfield
Alternativly: Is there a better way to modify a database record? Currently I'm trying to set all values into a new form.

Put the value that you want selected in the locations attribute of your $model and after rendering, it will be pre-selected in the radio list. That is:
$model->locations = ....
I assume that locations is a foreign key to some other table (or maybe a fixed list of strings).

Referring the documentation :
Pass the second parameter, options[] to radioList()
$options = [
'item' => function($index, $label, $name, $checked, $value) {
// check if the radio button is already selected
$checked = ($checked) ? 'checked' : '';
$return = '<label class="radio-inline">';
$return .= '<input type="radio" name="' . $name . '" value="' . $value . '" ' . $checked . '>';
$return .= $label;
$return .= '</label>';
return $return;
}
]
<?= $form->field($model, 'locations')
->radioList($regionen, $options)
->label('Regionen');
Hope this helps..

Related

How can i solve my codeigniter batch update problem?

Hello guys I just want to ask in my project there are three tables product, color and product_color.I insert database using insert_batch then it work fine, when i update product_color table using update_batch then face some problems.Here's my sample code:
Database:
product:id,name,sku...
color:id,color_name
product_color:id,pro_id,color_id
Input Form:
<?php foreach($colors as $color): ?>
<input type="checkbox" class="form-check-input" name="color[]" value="<?php echo $color->color_id; ?>" <?php foreach ($productcolor as $key => $value){ $array[] = $value->color_id;} if(in_array($color->color_id,$array)) echo 'checked'; else ''; ?>>
<label class="form-check-label">
<?php echo $color->color_name; ?>
</label>
<?php endforeach; ?>
Actually i want to pass primary id from product_color table.Here i pass color_id.Have any way to pass primary id from input form;
Here Is my Controller:
$colorBatch = array();
foreach ($color as $colorvalue) {
$colorBatch[] = array(
'id'=>$id
'pro_id' =>$pid,
'color_id' => $colorvalue
);
}
$this->db->update_batch('product_color', $colorBatch,'pro_id');
Where $pid contains product_id;
Is it possible to pass product_color table primary id from input form or Have any better solution to solve this.Sorry for bad english.
Thanks
Please check below code as your array structure is wrong;
$colorBatch = array();
foreach ($color as $key => $colorvalue) {
$colorBatch[$key] = array(
'id'=>$id
'pro_id' =>$pid,
'color_id' => $colorvalue
);
}
$this->db->update_batch('product_color', $colorBatch,'pro_id');

Radio Button group separately in yii2 without using radiolist

I need Radio Button group in separate place in yii2 like in this question . I can customise the radio button like in this picture
but when I submit the form only the value of last radio is always submitted if last radio button is clicked respective value else null . I am not able to submit previous checked value.
mine form looks like
<div class="cart-form">
<?php $form = ActiveForm::begin(); ?>
<?= $form->field($model, 'product_id')->hiddenInput()->label(false) ?>
<?= $form->field($model, 'size_id')->dropDownList(
ArrayHelper::map(Productsize::find()->where(['product_id'=>$id])->all (), 'product_size_id', 'product_size' ),
[ 'prompt'=>'Select size',
'onchange'=>'
$.get( "'.Yii::$app->urlManager->createUrl('cart/lists?id=').'"+$(this).val(),
function( data ) {
$( "#pricetag11" ).val(data);
$( "#pricetaghtml" ).html(data);
});
']); ?>
<?php $colors = Productcolor::find()->where(['product_id'=>$id])->all(); ?>
<h4>Price:</h4> <p id="pricetaghtml" style="color:red;"></p>
Select size to see the price
<?php echo $form->field($model, 'price_id')->hiddenInput(['id'=>'pricetag11'])->label(false)?>
<!-- here is my problem -->
<h4>Color:</h4>
<?php foreach($colors as $color):?>
<div style="background-color:<?= $color->product_color;?>;width:20px;height:20px;padding-left:3px; display: inline-block"> <?= $form->field($model, 'color_id')->radio(['value' =>$color->product_color, 'label'=>'','uncheck'=>'null']); ?></div>
<?php endforeach;?>
<!-- -->
<?= $form->field($model, 'quantity')->textInput(['type' => 'number','min'=>'0','max'=>'9999' , 'placeholder'=>'0']) ?>
<div class="form-group">
<?= Html::submitButton($model->isNewRecord ? 'Create' : 'Update', ['class' => $model->isNewRecord ? 'btn btn-success' : 'btn btn-primary']) ?>
</div>
<?php ActiveForm::end(); ?>
</div>
In my scenario, I have to load color (hexcode) from database table and display in form and need to save the respective code in another table using radio button.
I have tried so many ways to accomplish this task in yii2 but i am not able. i hope someone will point me to the right direction.
I guess this will work,
<?= $form->field($model, 'color_id')->radioList(
$colors,
[
'item' => function($index, $label, $name, $checked, $value) {
$return = '<div style="background-color:'.$value.';width:20px;height:20px;padding-left:3px; display: inline-block">';
$return .= '<input type="radio" name="' . $name . '" value="' . $value . '">';
$return .= '</div>';
return $return;
}
]
)
->label(false); ?>

Yii2: How to validate a form with multiple instances of the same model

In my form I update more start and end dates from the same model at once. See the simplified form:
<?php $form = ActiveForm::begin(); ?>
<?php foreach($dates as $i=>$date): ?>
<?= $form->field($date,"[$i]start"); ?>
<?= $form->field($date,"[$i]end"); ?>
<?php endforeach; ?>
</table>
<?= Html::submitButton('Save'); ?>
<?php ActiveForm::end(); ?>
In the model I need to control, if the end date is after the start date:
public function rules() {
return [
[['end'], 'compare', 'compareAttribute' => 'start', 'operator' => '>', 'message' => '{attribute} have to be after {compareValue}.‌'],
];
}
I tried to change selectors similarly as described in: Yii2: Validation in form with two instances of same model, but I was not successful. I suppose I need to change the 'compareAttribute' from 'mymodel-start' to 'mymodel-0-start' in the validation JS:
{yii.validation.compare(value, messages, {"operator":">","type":"string","compareAttribute":"mymodel-start","skipOnEmpty":1,"message":"End have to be after start.‌"});}
So, I look for something like:
$form->field($date,"[$i]end", [
'selectors' => [
'compareAttribute' => 'mymodel-'.$i.'-start'
]
])
Solution
The solution is based on the answer of lucas.
In the model I override the formName() method, so for every date I have a unique form name (based on ID for the existing dates and based on random number for new dates):
use ReflectionClass;
...
public $randomNumber;
public function formName()
{
$this->randomNumber = $this->randomNumber ? $this->randomNumber : rand();
$number = $this->id ? $this->id : '0' . $this->randomNumber;
$reflector = new ReflectionClass($this);
return $reflector->getShortName() . '-' . $number;
}
The form then looks like this:
<?php $form = ActiveForm::begin(); ?>
<?php foreach($dates as $date): ?>
<?= $form->field($date,"start"); ?>
<?= $form->field($date,"end"); ?>
<?php endforeach; ?>
</table>
<?= Html::submitButton('Save'); ?>
<?php ActiveForm::end(); ?>
Override the formName() method in your model class to make it unique. If you don't want to change your model class, create a subclass of it for the purpose of working for this controller action. After doing this, the html ID and name fields will automatically be unique.

How to add valueless attribute to <form> tag using yii2 ActiveForm

How do I add a value-ess attribute to the form tag?
I want to have:
<form data-abide >
according to: http://foundation.zurb.com/sites/docs/abide.html
I've tried
<?php $form = ActiveForm::begin(['id' => 'contact-form', 'options'=>['data-abide'=>'']]); ?>
but get output:
<form data-abide="ak8hvf-abide" >
Try this:
'options'=>['data-abide'=>true]
Reference: In the framework helper BaseHtml.php file, find :
function renderTagAttributes
Where :
foreach ($attributes as $name => $value) {if (is_bool($value)) { if ($value) { $html .= " $name"; } } elseif...
...
elseif ($value !== null) { $html .= " $name=\"" . static::encode($value) . '"'; }
...
It is actually behaving as expected - turns out it is the adide.js which adds the extra security token:
https://github.com/yiisoft/yii2/issues/10532#issuecomment-169952232
Thanks everyone for help!
For me, both 'data-abide'=>'' and 'data-abide'=>true works fine...
Could it be something outdated? Can you try run a composer update in your project?

joomla 3.1 dropdown in custom component

how do I create a dropdown list in joomla 3.1 for a custom component. I try to create custom fields and I would like to use joomlas dropdown with search
my get input method looks
public function getInput() {
$jinput = JFactory::getApplication()->input;
$sub_id = $jinput->get('sub_id');
$db = JFactory::getDbo();
$query = $db->getQuery(true)
->select('*')
->from('#__unis_faculties')
//->join('#__unis_subjects')
->order('faculty_name');
$db->setQuery($query);
$rows = $db->loadObjectList();
if (isset($sub_id)) {
$actual = $db->getQuery(true)
->select('f.id, f.faculty_name')
->from('#__unis_faculties AS f')
->join('LEFT', '#__unis_subjects AS s ON f.id = s.faculty')
->where('f.id = ' . $sub_id);
$db->setQuery($actual);
$actual_row = $db->loadRow();
}
$html = '';
$html .= '<div class="span12 input-prepend">
<span class="add-on">€ </span>
<input class="span4" name="price" id="price" type="text" />
</div>';
$html .= '<field name="" type="list" default="" label="Select an option" description=""><select>';
foreach ($rows as $row) {
$html .= '<option ' . "selected" ? $row->id = $actual_row->id : '' . 'value="' . $row->id . '" >' . $row->faculty_name . '</option>';
}
$html .= '</select></field>';
return $html;
}
but this does not outputs the desired result, the list won't shows up
the actual code is producing the following dropdown but without to show the elements