question-mark
Stuck on an issue?

Lightrun Answers was designed to reduce the constant googling that comes with debugging 3rd party libraries. It collects links to all the places you might be looking at while hunting down a tough bug.

And, if you’re still stuck at the end, we’re happy to hop on a call to see how we can help out.

Select(2) for grouped options

See original GitHub issue

This is just something I thought might come up for others but didn’t see a pre-made option available.

I often have options that apply to a model that need to be grouped to avoid confusion.

For example, a Contact might belongTo a Subcategory, which in turn belongTo’s a Category. Frequently, these subcategories have similar names making it impossible to identify which category they represent.

A field I find myself using regularly is a grouped select2 list, which needs to query the top level model (ie Category), and then display it’s relations (ie Subcategory) as the actual options in <optgroup>s…

I’m absolutely certain other’s might have a better way to implement this but this was how I did it for reference:

Setup:

	$this->crud->addField([
                         'name'  => 'subcategory_id', 
                         'label' => "Subcategory",
		         'type'  => 'select2_grouped', 
                         'entity' => 'subcategory', // Child model entity related to active model (belongsTo) (as per normal use)
                         'attribute' => 'title', // Attribute on child model to use as option label
		         'model' => 'App\Models\Category',  // Parent model
                         'group_label_attribute' => 'title',     // Attribute from parent model to use as optgroup label
                         'group_entity' => 'subcategories' // Child entity from perspective of parent model used as the list <options> (hasMany)
                     ]);

View:

// -- /resoruces/views/vendor/backpack/crud/fields/select2_grouped.blade.php
// -- Beginning and end of standard select2 option clipped...
<select
        name="{{ $field['name'] }}"
        @include('crud::inc.field_attributes', ['default_class' =>  'form-control select2'])
        >

            @if ($entity_model::isColumnNullable($field['name']))
                <option value="">-</option>
            @endif
             
            @if (isset($field['model']) && isset($field['group_entity']))
                @foreach ($field['model']::with($field['group_entity'])->get() as $connected_entity_entry)
                    <optgroup label="{{ $connected_entity_entry->{$field['group_label_attribute']} }}">
                        @foreach ($connected_entity_entry->{$field['group_entity']} as $subconnected_entity_entry)
                            <option value="{{ $subconnected_entity_entry->getKey() }}"
                                @if ( ( old($field['name']) && old($field['name']) == $subconnected_entity_entry->getKey() ) || (isset($field['value']) && $subconnected_entity_entry->getKey()==$field['value']))
                                     selected
                                @endif
                            >{{ $subconnected_entity_entry->{$field['attribute']} }}</option>
                        @endforeach
                    </optgroup>
                @endforeach
            @endif
    </select>

Example: image

Issue Analytics

  • State:closed
  • Created 7 years ago
  • Reactions:7
  • Comments:7 (4 by maintainers)

github_iconTop GitHub Comments

1reaction
tabacitucommented, Aug 30, 2022

Hi @samsebastian , @drmmr763 , @AbbyJanke ,

On second thought, I think @drmmr763 makes a very good point. From that point of view, we should provide support for optgroup - it is part of the HTML standard.

I’ve just created two new fields types for this - select_grouped and select2_grouped. Their definition is a little different from yours @samsebastian , since they first get the Category, then Elements for each category. But the result should be the same - options grouped by another entity.

Let me know what you think here: https://github.com/Laravel-Backpack/CRUD/pull/1688 Will be released as part of the 3.5 update - later this week.

Cheers! Thanks for the feedback.

0reactions
pxpmcommented, Aug 30, 2022

Hello @elenadanevska

I’v just added: https://github.com/Laravel-Backpack/ideas/issues/202

I think it’s something usefull to have. I think the main differences in the select is that the name that needs to be: selectName[], and select needs the multiple attribute defined.

If you in the meanwhile code a solution for this and are willing to share with others, please open a Pull Request, and we will review it.

Thanks, Pedro

Read more comments on GitHub >

github_iconTop Results From Across the Web

Options | Select2 - The jQuery replacement for select boxes
Select2 is a jQuery based replacement for select boxes. It supports searching, remote data sets, and pagination (infinite scrolling) of results.
Read more >
Selectable optgroup using select2 - jquery - Stack Overflow
To make a group option selectable, you must give it an "id", but it appears it can be an empty string. You can...
Read more >
Options - Select2 - JeeSite
Select2 supports a wide variety of options that allow you to customize it to ... You can emulate grouping by using an <option>...
Read more >
Use groups with select2.js. Clicking a group name adds all ...
Use groups with select2.js. Clicking a group name adds all sub-items. - select2-groups.js.
Read more >
optgroup and select2 - CodePen
HTML (Slim) · HTML Options ; CSS · CSS Options ; JS (CoffeeScript) · JS Options.
Read more >

github_iconTop Related Medium Post

No results found

github_iconTop Related StackOverflow Question

No results found

github_iconTroubleshoot Live Code

Lightrun enables developers to add logs, metrics and snapshots to live code - no restarts or redeploys required.
Start Free

github_iconTop Related Reddit Thread

No results found

github_iconTop Related Hackernoon Post

No results found

github_iconTop Related Tweet

No results found

github_iconTop Related Dev.to Post

No results found

github_iconTop Related Hashnode Post

No results found