Yii2: Kartik Select2: Initial Value from Model Attribute - csv

I have a Model who has a column (attribute) that stored a comma separated value of IDs.
For Example,
Movie has a column "Genre" that includes more than one genre, e.g.: 40,20,1,3
How can I use Select2 widget to show these values separated when 'multiple' => true
And how can I save them back into comma-separated value as a string. I want a solution that will allow for quick flexibility. I know you can implode and explode the string but seems too much.
Any help appreciated

If I remember correctly pass the default option as part of the $options configuration for the widget:
echo $form->field($model, 'model_attribute_name')->widget(Select2::className(), [
'data' => $data
'options' => [
'class' => 'form-control',
'placeholder' => 'Choose Option...',
'selected' => 40
],
'pluginOptions' => [
'allowClear' => true,
],
])->label('Select2 Form Field');
This is from memory for grain fo salt here. The documentation at http://demos.krajee.com/widget-details/select2 is not very specific about how to do this.

I don't believe you can do that. Select2 sends the data in post as an array, so you would still need to use implode before saving. What i would do instead is in your model class:
class MyModel extends \yii\db\ActiveRecord {
$public myArrayAttribute;
...
public function beforeSave($insert) {
if (parent::beforeSave($insert)) {
$this->myAttribute = implode(',', $this->myArrayAttribute);
return true;
}
return false;
}
public function afterFind() {
parent::afterFind();
$this->myArrayAttribute = explode(',', $this->myAttribute);
}
}
This way myArrayAttribute will hold the values from the comma separated field as an array. Of course you will need to add validation rules for it and use it instead of your other attribute in create and update forms.

if you're displaying a form with already populated fields, maybe you want to update an already existing object, and you want to display the already saved value for the Select2 field, use 'data' => [ 1 => 'Some value' ], where 1 is the value, associated to the value displayed in the form. You can retrieve stuff to put in data from DB beforehand.
Source: https://github.com/kartik-v/yii2-widget-select2/issues/37

Related

How to do a breakline in yii2?

I'm trying to combine two data into one column. I already managed to combine two data in one column. But my problem is I don't know how to do a break line to separate the data. I have tried this way but doesn't work.
This is my code
'NAME_PROG_ENG'.'REMARKS' => ['label' => "Programme Name",'value' => function ($data) {return ($data->NAME_PROG_ENG)."\r\n".nl2br("Previously known as: ".($data->REMARKS));}],
I think you refer to GridView component.
Some explanation:
'NAME_PROG_ENG'.'REMARKS' =>
the array index is the model field name, you can't combine 2 columns just by concatenating the column name. In this way you just define a column in the grid wich is not connected to the model. This is not an error, is just to notice that this does not give you the expected result.
'value' => function ($data) {return ($data->NAME_PROG_ENG)."\r\n".nl2br("Previously known as: ".($data->REMARKS));}
Between $data->NAME_PROG_ENG and $data->REMARKS you put a "\r\n" which is fine, but you apply nl2br() function only to the second part of the string.
Now about Gridview. Text are automatically converted to entities, this is a security feature to avoid script injection from user input. If you plan to use input from an untrusted user, ensure that you clean it using htmlpurifier before saving it in database or before showing it (in your 'value'=>... function)
https://www.yiiframework.com/search?language=en&version=2.0&type=guide&q=htmlpurifier
You can bypass html entity conversion by specifies the output format as raw in grid column option
'format'=>'raw'
So you column definition should be something like
'prog_and_remark_combined' => [
'format' => 'raw',
'label' => "Programme Name",
'value' => function ($data) {
return nl2br(
$data->NAME_PROG_ENG .
"\r\nPreviously known as: " .
$data->REMARKS
);
}
],
Gridview allow a short notation
https://www.yiiframework.com/doc/api/2.0/yii-grid-gridview#$columns-detail
which is like this
<column name>:<fomat>:<label>
your code can be as follow as well
'prog_and_remark_combined:raw:Programme Name' => [
'value' => function ($data) {
return nl2br(
$data->NAME_PROG_ENG .
"\r\nPreviously known as: " .
$data->REMARKS
);
}
],
Last note, if the fields does not contain new line to be converted, just concatenate them without using nltobr() function
return $data->NAME_PROG_ENG . "<br>Previously known as: " . $data->REMARKS

Saving data to the join table using control options in CakePHP 3.x

I learned here how one can save the data to the fields of join table CoursesMemberships while adding or editing a student in CakePHP 3.x. In order to add grades for many courses I can do this in my add and edit forms:
echo $this->Form->control('courses.0.id', ['type' => 'select', 'options' => $courses]);
echo $this->Form->control('courses.0._joinData.grade');
echo $this->Form->control('courses.1.id', ['type' => 'select', 'options' => $courses]);
echo $this->Form->control('courses.1._joinData.grade');
echo $this->Form->control('courses.2.id', ['type' => 'select', 'options' => $courses]);
echo $this->Form->control('courses.2._joinData.grade');
...
but this form:
has a fixed number of courses for each student;
requires to select the course id from the list ('type' => 'select');
adds all courses to the student record even if not attended (well, the corresponding grade field can be kept empty, but still).
Is there a way to have a simpler form, where all courses are listed and one can only checkbox the course attended and enter the corresponding grade? I found it very challenging using control...
EDIT:
After #ndm suggested a very nice method below, I implemented it in the add.ctp:
foreach ($courses as $key => $course) {
echo $this->Form->control('courses.'.$key.'.id', ['type' => 'checkbox', 'hiddenField' => false, 'value' => $key,
'label' => $key]);
echo $this->Form->control('courses.'.$key.'._joinData.grades');
}
and corrected StudentsTable.php accordingly. And it runs with no problems.
However, if I do the same in edit.ctp, the previously saved records (e.g. for 1, 3, 5 and 7 courses are now listed as 1, 2 and 3 showing the grades for former 3rd 5th and 7th courses and the form forces me to check those three boxes. I understand that the first record disappeared because my courses start with id=1 (and so does the $key in the loop) and 'courses.0.id' is thus missing, but the general problem is that the empty fields removed by beforeMarshal function are no longer recognized in edit.ctp form and I cannot find a reasonable way to edit the student's record.
There is no build in support for what you are trying to achieve, you'll have to come up with a custom solution, which will likely either require a mixture of form and marshalling logic, or JavaScript.
You could create for example a list of checkboxes, and use the id value (wich will be zero in case the checkbox isn't checked, or the ID in case it is checked) to remove unchecked entries from the submitted data before marshalling, something like this:
echo $this->Form->control('courses.0.id', [
'type' => 'checkbox',
'value' => $courses[0]->id,
'label' => $courses[0]->title
]);
echo $this->Form->control('courses.0._joinData.grade');
echo $this->Form->control('courses.1.id', [
'type' => 'checkbox',
'value' => $courses[1]->id,
'label' => $courses[1]->title
]);
echo $this->Form->control('courses.1._joinData.grade');
// ...
// in the `StudentsTable` class
public function beforeMarshal(\Cake\Event\Event $event, \ArrayObject $data, \ArrayObject $options)
{
forach ($data['courses'] as $key => $course) {
if (empty($course['id'])) {
unset($data['courses'][$key])
}
}
}
Alternatively you could use JavaScript to disable the controls related to the checkbox so that they aren't being submitted in the first place. For this to work properly you'll need to make sure that you disable the hidden field that is by default being generated for checkboxes (see the hiddenField option), as otherwise zero will be sent for unchecked checkboxes.
Here's a quick, untested jQuery example to illustrate the principle:
echo $this->Form->control('courses.0.id', [
'class' => 'course-checkbox',
'data-join-data-input' => '#course-join-data-0',
'type' => 'checkbox',
'hiddenField' => false, // no fallback, unchecked boxes aren't being submitted
'value' => $courses[0]->id,
'label' => $courses[0]->title
]);
echo $this->Form->control('courses.0._joinData.grade', [
'id' => 'course-join-data-0',
'disabled' => true
]);
// ...
$('.course-checkbox').each(function () {
var $checkbox = $(this);
var $joinDataInput = $($checkbox.data('join-data-input'));
$checkbox.on('change', function () {
$joinDataInput.prop('disabled', !$checkbox.prop('checked'));
});
});
See also
Cookbook > Database Access & ORM > Saving Data > Modifying Request Data Before Building Entities
Cookbook > Views > Helpers > Form > Creating Select, Checkbox and Radio Controls > Options for Control
Cookbook > Views > Helpers > Form > Creating Select, Checkbox and Radio Controls > Creating Checkboxes

Pass dynamic params in the ajax call of yii2-grid EditableColum widget

the \kartik\grid\EditableColumn widget has a parameter called ajaxSettings where you may override the parameters passed with the ajax request to the server. What i want to do is to dynamically pass the selected rows ids together with the value coming from the popover to the server. I manage to do that passing static parameter coming from a php array in compile time like so
Editable::widget(['name' => 'publishDate', 'ajaxSettings' => ['ids' => [1,2,3]]])
but It seems that i cannot use a jquery selector there to grab the ids of the selected columns like so
Editable::widget([
'name' => 'publishDate',
'ajaxSettings' => [
'ids' => '$("#books-grid").yiiGridView("getSelectedRows")'
]
])
Maybe you want to try creating a variable outside the Editable::widget([ like this:
var arrayIds = $("#books-grid").yiiGridView("getSelectedRows");
And then assign it to the widget:
Editable::widget([
'name' => 'publishDate',
'ajaxSettings' => [
'ids' => arrayIds
]
])
Hope this helps,
Leo.

Yii2 Behaviors / Scenarios Modify Attribute

I have a model "Product" that I would like to modify or "mutate" one of its attributes for, but only in specific instances.
I store attribute, price as an integer. So $1.99 gets stored as 199.
I would like to incorporate this with the activeForm in such a way that when getting the price it converts to "1.99" in the field (visually). But when I submit the form, before validation, it modifies the price from "1.99" to "199".
I'm assuming this will require Behaviors, and specifically attaching a behavior to the model before creating the active form. However, I'm still confused on how to set this up. I see there is an AttributeBehavior class or I can make my own Behavior class, but I've been having trouble figuring out implementation in this case.
The situation:
foreach ($store_item->storeProducts as $i=>$product) {
?>
<tr>
<td>
<?= $form->field($product, '['.$i.']price')->label(false); ?>
</td>
</tr>
<?php
$i++;
}
?>
Here is a scenario where I check for empty attribute and assign value before saving. Note owner returns the Model so that you can access model attributes and functions that are public. Let me know if I can explain anything further
public function behaviors()
{
return [
[
'class' => AttributeBehavior::className(),
'attributes' => [
ActiveRecord::EVENT_BEFORE_INSERT => 'yourAttrib',
],
'value' => function ($event) {
$code = "N/A";
if(!empty($this->owner->yourAttrib))
{
$code = $this->owner->yourAttrib; //here change your attribute accordingly
}
return $code;
},
],
//other behaviors
];
}
You could simply use a getter/setter, e.g. :
public function getRealPrice()
{
return $this->price/100;
}
public function setRealPrice($value)
{
$this->price = $value*100;
}
And don't forget to :
add realPrice in your model's rules,
use realPrice in your form (instead of price).

Changing value of an attribute in DetailView widget

I have a table named Play and I'm showing details of each record in Yii2 detail view widget. I have an attribute in that table recurring which is of type tinyint, it can be 0 or 1. But I don't want to view it as a number, instead i want to display yes or no based on the value (0 or 1).
I'm trying to change that with a function in detailview widget but I'm getting an error: Object of class Closure could not be converted to string
My detail view code:
<?= DetailView::widget([
'model' => $model,
'attributes' => [
'name',
'max_people_count',
'type',
[
'attribute' => 'recurring',
'format'=>'raw',
'value'=> function ($model) {
if($model->recurring == 1)
{
return 'yes';
}
else {
return 'no';
}
},
],
'day',
'time',
...
Any help would be appreciated !
Unlike GridView which processes a set of models, DetailView processes just one. So there is no need for using closure since $model is the only one model for display and available in view as variable.
You can definitely use solution suggested by rkm, but there is more simple option.
By the way you can simplify condition a bit since the allowed values are only 0 and 1:
'value' => $model->recurring ? 'yes' : 'no'
If you only want to display value as boolean, you can add formatter suffix with colon:
'recurring:boolean',
'format' => 'raw' is redundant here because it's just text without html.
If you want add more options, you can use this:
[
'attribute' => 'recurring',
'format' => 'boolean',
// Other options
],
Using formatter is more flexible approach because these labels will be generated depending on application language set in config.
Official documentation:
DetailView $attributes property
Formatter class
Formatter asBoolean() method
See also this question, it's quite similar to yours.
Try
'value' => $model->recurring == 1 ? 'yes' : 'no'