Setting kartik switch input true and false value - yii2

Am using yii2 kartik switch input and I would like to set the switch input true and false value explicitly
This is the switch input
<?php
echo $form->field($model, 'PR_Status_ID')->widget(SwitchInput::classname(), [])->label(false);;
?>
Am using the switch input for updating a field and i would like the switch input to be off if the value of $model PR_Status_ID is 6 and on if the value is 7
How can I implement this?

Just set the initial value based on the PR_Status_ID field for update case:
echo $form->field($model, 'PR_Status_ID')->widget(SwitchInput::classname(), [
'value' => (!$model->isNewRecord && $model->PR_Status_ID == 6) ? false : true,
])->label(false);

Related

Pre-population of checkboxList with DynamicModel issue

I have created a DynamicModel to build a search form which contains a checkboxList with the items being populated by the records of a model. The form works fine, however the form appears on the results page and all fields are populated with the previously selected values apart from the checkboxList.
Controller:
$model = DynamicModel::validateData(
['date_from',
'date_to',
'client_site',
'report_types',
]);
$model->addRule(['client_site'], 'integer');
$model->addRule(['client_site', 'report_types'], 'required');
$model->addRule(['date_from','date_to'], 'string');
$model->load(Yii::$app->request->post()) && $model->validate();
$reportTypes = ArrayHelper::map(ReportType::find()->asArray()->all, 'id', 'name');
return $this->render('print-report-form', [
'report_types' => $reportTypes,
'model' => $model,
]);
View:
<?= $form->field($model, 'report_types[]')
->inline(false)
->checkboxList($reportTypes);
?>
Do I need to tie the $reportTypes in within the model another way? Any ideas on why the selected checkboxes are not being pre-populated on the form submission?
First of all, there is a mistake in view form field, variable name is wrong, it should be
<?= $form->field($model, 'report_types[]')
->inline(false)
->checkboxList($report_types);
?>
then in controller
$model = DynamicModel::validateData(
['date_from',
'date_to',
'client_site',
'report_types',
]);
$model->addRule(['client_site'], 'integer');
$model->addRule(['client_site', 'report_types'], 'required');
$model->addRule(['date_from','date_to'], 'string');
$posted_model = clone $model;
$reportTypes = ArrayHelper::map(ReportType::find()->asArray()->all, 'id', 'name');
if($posted_model->load(Yii::$app->request->post()) && $posted_model->validate())
{
// save data or do as per your requirement with $posted_model
// if nothing to be done, and just rendering back to form then
return $this->render('print-report-form', [
'report_types' => $reportTypes,
'model' => $model, // line X
]);
}
else
{
return $this->render('print-report-form', [
'report_types' => $reportTypes,
'model' => $model, // line X
]);
}
This was happening because when the view was rendering the very first time, all checkbox are empty, but when submit the form the model gets filled up with POSTed data ie all its attribute are set and then always you were rendering POSTed model ie the model filled with data.
Now with the above situation you are not rendering POSTed model, you are always rendering empty new model.
This was the situation where you need empty checkbox.
Second Situation:
If you need checkbox to be prepopulated then
remove [] in form field
<?= $form->field($model, 'report_types')
->inline(false)
->checkboxList($report_types);
?>
and replace line X by
'model' => $posted_model,
Here you will get filled checkboxes

Kartik DepDrop at update form not working in Yii2

For example, we have an update form with the fields
<?= $form->field($model, 'company_name')->dropDownList($data,
['prompt' => 'Select Company Name..', 'id' => 'cat-id']
) ?>
<?php
echo $form->field($model, 'employee_name')->widget(DepDrop::classname(), [
'options'=>['id'=>'subcat-id'],
'pluginOptions'=>[
'initialize' => true,
'depends'=>['cat-id'],
'placeholder'=>'Select...',
'url'=>yii\helpers\Url::to(['claim/subcat'])
]
]);
?>
A value of depended dropdown is not set when the first dropdown has a value ($cat-id). It shows placeholder "Choose a model" instead of list of models for current manufacturer. The same happens, when depended dropdown also have a value ($model->model_id). It is not showed. Only placeholder "Choose a model" is showed
You must do one of the following for update:
Option 1: Set data property array for dependent dropdown to have a preset dependent list on init.
Option 2: Set pluginOptions['initialize'] property to true for dependent dropdown. This will run the ajax calls on init to generate the dropdown list.

Yii2 dropdown selected value

I want to show selected value in Yii2 dropdown,
$_GET Value:
$id = $_GET["cid"];
Drop down code
$form->field($model, 'userid')
->dropDownList(
[User::getUser()],
//[ArrayHelper::map(User::findAll(['active' => '1']), 'id', 'name')],
['prompt'=>'Select a user','id'=>'user_dropdown'],
['options' =>
[
$id => ['selected' => true]
]
]
)->label('');
but this method is not working!
Try this.
$model->userid=$id;
$form->field($model, 'userid')
->dropDownList(...)
->label('');
Basically, you affect the options (your <option> elements) by using the value attribute's actual value as the array key in the dropDownList options array.
So in this case I have an array of states and the value attributes have the state abbreviation, for example value="FL". I'm getting my selected state from the Address table, which stores the abbreviation, so all I have to do is use that as my array key in the options array:
echo $form->field($model, 'state')->dropDownList($listData, ['prompt'=>'Select...', 'options'=>[$address->state=>["Selected"=>true]]]);
The documentation spells it out: http://www.yiiframework.com/doc-2.0/yii-helpers-basehtml.html#dropDownList()-detail
i hope this will help you
$form->field($model, 'userid')
->dropDownList(
[User::getUser()],
//[ArrayHelper::map(User::find()->where('id' => $id)->all(), 'id', 'name')],
['prompt'=>'Select a user','id'=>'user_dropdown'],
['options' =>
[
$id => ['selected' => true]
]
]
)->label('');
$model->userid = $_GET['cid'];
$form->field($model, 'userid')
->dropDownList(
$items, //Flat array('id'=>'val')
['prompt'=>''] //options
)->label('');
<?php
$selectValue = $_GET['tid']
echo $form->field($model, 'tag_id')
->dropdownList(
ArrayHelper::map(Tag::find()->where(['visibility'=>'1'])->orderBy('value ASC')->all(), 'tag_id', 'value'),
['options' => [$selectValue => ['Selected'=>'selected']]],
['prompt' => '-- Select Tag --'])
->label(false);
?>
This code will Auto Select the selected value received as input.
Where $selectValue will be numeric value received from GET method.
Final output : <option value="14" selected="selected">NONE</option>
Ok, if you are using ActiveForm then value of your model field will be used as the selected value. With Html helper dropDownList function accepts another parameter selection doc. Example:
$id = $_GET["cid"];
\yii\helpers\Html::dropDownList('userid', $id, [ArrayHelper::map(User::findAll(['active' => '1']), 'id', 'name'), [......])
This is my S.O.L.I.D approach.
Controller
$model = new User();
$model->userid = $id; #this line does the magick. Make sure the $id has a value, so do the if else here.
return $this->return('view', compact('model'))
But, if you prefer the setter method. Do this...
# Model
class User extends ActiveRecord
{
public function setUserId(int $userId): void
{
$this->userid = $userId;
}
}
# Controller
$model = new User();
$model->setUserId($userId);
View (view is as-is)
$form->field($model, 'userid')
->dropDownList(...)
->label('');
Use this code below:
$category = \backend\models\ProductCategory::find()->WHERE(['deleted'=>'N'])->all();
$listData = ArrayHelper::map($category,'product_category_id','category_name');
echo $form->field($model, 'product_category_id')->dropDownList($listData,['prompt'=>'Select']);
All of the options I've added are unrequired.
What is written in the 'value' index is what dropdown item will be selected as default.
Prompt just displays a first option that doesn't have a value associated with it.
echo $form->field($model, 'model_attribute_name')
->dropDownList($associativeArrayValueToText,
[
'value'=> $valueIWantSelected,
'prompt' => 'What I want as a placeholder for first option',
'class' => 'classname'
]);
You'll find the function that assigns this in the following file:
vendor/yiisoft/yii2/helpers/BaseHtml.php
public static function renderSelectOptions($selection, $items, &$tagOptions = [])
Also from the function you can see that you can add an optgroup to your dropdown, you just need to supply a multidimensional array in where I've put $associativeArrayValueToText. This just means that you can split your options by introducing group headings to the dropdown.

How do I set a maxlength for Codeigniters form_textarea()?

I am trying to set a maxlength for the form_textarea() in Codeigniter.
I tried the following:
<?php
$options = array(
'maxlength' => '100'
);
?>
<tr>
<td><?= form_label('Profiel:');?></td>
<td><?= form_textarea('Profiel', $options, $info['Profiel']);?></td>
</tr>
When I edit my form to edit the text in the textarea it says Array. So the text is gone and is replaced with Array.
But that is not working.
Maybe I have to use Jquery?
Codeigniter allows you to pass attributes into your form elements by way of an associative array.
Documentation for the form helper is here: http://ellislab.com/codeigniter/user-guide/helpers/form_helper.html
Although I can see exactly what you're trying to do, there's one caveat with textareas. From the documentation:
form_textarea()
This function is identical in all respects to the form_input()
function above except that it generates a "textarea" type. Note:
Instead of the "maxlength" and "size" attributes in the above example,
you will instead specify "rows" and "cols".
So, you need to pass rows and columns instead of maxlength for textareas. Your code would look something like this:
$options = array(
'rows' => 10,
'cols' => 10
);
form_textarea(array(
'cols' => 1,
'rows' => 1
));

How to set cakephp radio-button from mysql?

This cakephp form used to edit a mysql record needs to load the state of a radio button from a mysql database.
The mysql payment_type is enum('Account', 'Credit').
All of the other non-radio-button form inputs reload from the database and payment_type is correctly displayed on another form using this:
<?php echo h($purchaseOrder['PurchaseOrder']['payment_type']); ?>
Why doesn't this correctly set the radio-button from payment_type?
$options = array('account' => 'Account', 'credit' => 'Credit');
$attributes = array('legend' => false, 'value' => 'payment_type');
echo $this->Form->radio('payment_type', $options, $attributes);
In your attribute array, you should assign value which you want to keep selected by default .
For example you want account to be selected by default then in value you should assign 'account'. So your final attribute will be:
$attributes = array('legend' => false, 'value' => 'account');