Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Selected option in Select2 #87

Closed
it3rmit opened this issue Jun 16, 2014 · 23 comments
Closed

Selected option in Select2 #87

it3rmit opened this issue Jun 16, 2014 · 23 comments
Labels

Comments

@it3rmit
Copy link

it3rmit commented Jun 16, 2014

Hi.
Is there an opportunity to specify the selected option for the select2 widget? It is very useful for editing field, that already have some value.

@kartik-v
Copy link
Owner

The widget automatically shows a selected value if you have set a value for the input (or the input has a value).

NOTE: The value set must be the id and not the displayed name.

@it3rmit
Copy link
Author

it3rmit commented Jun 16, 2014

Actually, this is not what I was asking about... For instance, I have category_1, category_2 and category_3.
I am creating an article and placing it in category 2. When I want to edit the category for the article I want to use select2 widget.
I want it to show me the actual value (category_2) before editing, but not to be blank.
If this is what you have meant, how can I specify the value to be shown.

@kartik-v
Copy link
Owner

Not sure why this is difficult - one of these options for example, could achieve what you want:

$data = [1=>'category 1', 2=>'category 2', 3=>'category 3'];
// without model
echo Select2::widget([
   'name' => 'category',
   'value' => 2, // value to initialize
   'data' => $data
]);

// alternatively with model
$model->category = 2;  // value to initialize
echo Select2::widget([
   'model' => $model,
   'attribute' => 'category',
   'data' => $data
]);

@it3rmit
Copy link
Author

it3rmit commented Jun 17, 2014

Thanks, this is what I was looking for. I couldn't find it in the docs the example without the model.

@kartik-v
Copy link
Owner

kartik-v commented Jun 17, 2014

Reading the docs is important... Select2 extends from the Yii Input Widget, which is highlighted in docs as well.

@JacquesMarques
Copy link

But how can I change selected option in Javascript after created the widget?

@kartik-v
Copy link
Owner

kartik-v commented Dec 2, 2014

Check the Select2 plugin documentation for details on various javascript options.

// set value
$("#select").select2("val", "CA");
// get value
$("#select").select2("val");

@JacquesMarques
Copy link

Hi, thanks for you attention.

I try this, but not work. In my script I create the widget like this:

            <?php
            // The controller action that will render the list
            $url = \yii\helpers\Url::to(['prospect-list']);

            // Script to initialize the selection based on the value of the select2 element
            $initScript = <<< SCRIPT
            function (element, callback) {
                var id=\$(element).val();
                if (id !== "") {
                    \$.ajax("{$url}?id=" + id, {
                        dataType: "json"
                    }).done(function(data) { callback(data.results);});
                }
            }

SCRIPT;

            // The widget
            echo $form->field($model, 'prospect_id')->widget(Select2::classname(), [
                'options' => ['placeholder' => 'Prospect a procurar ...'],
                'pluginOptions' => [
                    'allowClear' => true,
                    'minimumInputLength' => 3,
                    'ajax' => [
                        'url' => $url,
                        'dataType' => 'json',
                        'data' => new JsExpression('function(term,page) { return {search:term}; }'),
                        'results' => new JsExpression('function(data,page) { return {results:data.results}; }'),
                    ],
                    'initSelection' => new JsExpression($initScript)
                ],
            ]);

            ?>

But with this what are the ID of select2 field? I try set the ID but nothing work.

Can you help me with this?

@JacquesMarques
Copy link

Finally I found a solution:

$("#agenda-prospect_id").select2("data", {id: results.prospect_id, text: results.prospect_nome});

I have to use the "data" not the "val" method...

Thanks.

@jatin7591
Copy link

How to set default value for the Select2 Widget when plugin option "multiple" => true...
i saved it in database by implode with ","

@KrunalHingu
Copy link

hello there.
i'm facing the problem to get selected options from database while using select 2 ,
select 2 is fetching only single option but when i store multiple option its not working properly.
you can see only one option i got selected but unable to get multiple selected values.
my code:

field($model, 'service_id')->widget(Select2::classname(),['data' => $listServices, 'value' => array_combine($model_services, $model_services), 'options' => ['placeholder' => 'Select Service...','multiple'=>'multiple'], 'pluginOptions' => ['allowClear' => true,], ]); ?>

will you please guide me.?
Thanks.
screenshot_1

@asimnzm
Copy link

asimnzm commented May 6, 2015

hi selected option in select2 for ajax not working in edit form it shows blank
following is my code
echo $form->field($model, 'customer_id')->widget(Select2::classname(), [
'options' => ['placeholder' => 'Search for a Customer ...'],

        'pluginOptions' => [
                'allowClear' => true,
                'minimumInputLength' => 2,
                'ajax' => [
                        'url' => $url,
                        'dataType' => 'json',
                        'data' => new JsExpression('function(term,page) { return {search:term}; }'),
                        'results' => new JsExpression('function(data,page) { return {results:data.results}; }'),
                ],
                'initSelection' => new JsExpression($initScript)
        ],
]);

@asimnzm
Copy link

asimnzm commented May 6, 2015

solved i just initialized the value in view
$initScript = <<< SCRIPT
function (element, callback) {
var search=$(element).val();

if (search !== "") {
    \$.ajax("{$url1}?search=" + search, {
        dataType: "json"
    }).done(function(data) { 

            callback(data.results[0]);

});
}
}
SCRIPT;

@hafeesbharathi
Copy link

if($id!=null):
$request->event_id=$id;
endif;
?>

field($request, 'event_id')->widget(Select2::classname(), [ 'data' =>$events, 'language' => '', 'options' => ['multiple' => false, 'placeholder' => 'Select Event'], 'pluginOptions' => [ 'allowClear' => true ], ])->label('Select Event'); ?>

@schreeedi
Copy link

@jatin7591: this worked for me

<?php
$selection = explode(",", $string_from_database);
$js = "";
foreach ($selection as $val) {
    $js .= "$('#w0 option[value=". $val ."]').attr('selected','selected').change();";
}
$this->registerJs($js, yii\web\View::POS_READY);
?>

In this case $string_from_database must be the values from the options comma-separated in one string.

@liamgcarter
Copy link

Hiya.

I am having an issue setting the selected value within the Select 2 widget
I am using it within the form widget and without a model

'province_id'=>['type'=>Form::INPUT_WIDGET, 'widgetClass'=>'\kartik\widgets\Select2', 'options'=>[ 'value'=>$_GET['search-form-sales']['province_id'], 'data'=> ArrayHelper::map(Province::find()->orderBy('text')->asArray()->all(), 'id','text'), 'value'=>50, 'options' => [ 'placeholder' => 'Province', ], 'pluginOptions' => [ 'allowClear' => true ], ],],

As you can see I have tried the $_GET property and now I have made the value static. The id 50 isn't set as selected, I have tried removing the placeholder and it then just displays the first option.

Any ideas

Regards

Liam

@hendrasyp
Copy link

Hi, thanks for this awesome widget. But I still can't selected default value. it happening when I try to update data:

// if model are newRecord
$data = ArrayHelper::map(ContactGroups::find()->where(['group_status'=>'ACTIVE'])->asArray()->all(),'group_id', 'group_name'); 

if (!$model->isNewRecord)
{
  $data = ArrayHelper::map(ContactGroups::find()->joinWith('contactContactGroups')->where(['group_status'=>'ACTIVE','contact_contact_groups.contact_id'=>$model->contact_id])->asArray()->all(),'group_id', 'group_name'); 
}

echo $form->field($model, 'group_id')->widget(Select2::classname(), [
                 'data' => $data,
                  'language' => 'en',
                  'options' => ['placeholder' => Yii::t('modules','Pilih Kelompok')],
                  'pluginOptions' => [
                    'tags'=>true,
                    'allowClear' => true,
                    'multiple' => true,
                  ],
              ])->label('Kelompok');

@Nasmy
Copy link

Nasmy commented Jan 11, 2017

Hi Guys. I have Solved this issue. Please try. nasmy_ayyash@yahoo.com

<?php
if(!$model->isNewRecord){
    $id=$model->id;
    //$speciality=ArrayHelper::map(\app\models\Doctorspeciality::find('doctorId')->all(),'id');
    $rows = (new \yii\db\Query())
        ->select(['specialityId'])
        ->from('Doctorspeciality')
        ->where(['doctorId' => $id])
        ->all();

    $result = ArrayHelper::getColumn($rows, 'specialityId');
}
?>
<?php
    echo '<label class="control-label">Speciality</label>';
    echo Select2::widget([
        'name' => 'speciality',
        'data' => ArrayHelper::map(\app\models\Speciality::find()->all(),'id','specialityName'),
        'value'=>(!$model->isNewRecord ? $result : ''),
        'options' => [
            'placeholder' => 'Select Speciality ...',
            'multiple' => true
        ],
        'pluginOptions' => [
            'allowClear' => true
        ],
    ]);
    ?> 

@Matijt
Copy link

Matijt commented May 5, 2017

Hi, I would like to know how can I do to display the information of the dropbox but being able to write the value. Just like if the dropdown would be examples of what could be in the text field. Like a history of what the user already wrote there, but he can write what he considers best for the occasion.

@srikanth15794
Copy link

srikanth15794 commented Sep 19, 2017

Can anyone please help me.. how can i select a default value on page load in select2 filed used in yii2 dynamic form widget ?

@Matijt
Copy link

Matijt commented Sep 19, 2017

srikanth15794

Something like this:

<?php
$model->category = 2;  // value to initialize
echo Select2::widget([
   'model' => $model,
   'attribute' => 'category',
   'data' => $data
]);
?>

#87

You just need to establish a value.

@iamahmudul
Copy link

Hello, I am looking for something that can be done using CJuiAutoComplete extension but here I want to use Eselect2, because I want a dropdown with a search option. But when selecting a value from dropdown, I want to populate 4 other fields. Is there any option in select2? By the way I'm using Yii1

@ghost
Copy link

ghost commented Mar 31, 2020

I had been suffering from using Select2 with a form + model. The issue at the end is very simple. You can not use an attribute in your model that is assigned to a DB field. You just create another attribute, add it to your rules as safe, then use this field:

$model->booksetsArray = ArrayHelper::getColumn($model->bookBooksets, 'bookset_id');

    echo $form->field($model, 'booksetsArray')->widget(Select2::classname(), [
    'data' => ArrayHelper::map($booksets, 'id', 'title'),
    'attribute' => 'booksetsArray',
    'language' => 'en',
    'options' => ['placeholder' => '--- Select ---', 'multiple' => true],
    'pluginOptions' => [
        'allowClear' => true,
        'tags' => true
    ],
    ]);

I will move setting booksetsArray to afterFind() method in the model, but it does the work.

I hope it helps someone.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
Projects
None yet
Development

No branches or pull requests