PHPackages                             brunops/select24entity-bundle - PHPackages - PHPackages  [Skip to content](#main-content)[PHPackages](/)[Directory](/)[Categories](/categories)[Trending](/trending)[Leaderboard](/leaderboard)[Changelog](/changelog)[Analyze](/analyze)[Collections](/collections)[Log in](/login)[Sign up](/register)

1. [Directory](/)
2. /
3. [Templating &amp; Views](/categories/templating)
4. /
5. brunops/select24entity-bundle

AbandonedArchivedSymfony-bundle[Templating &amp; Views](/categories/templating)

brunops/select24entity-bundle
=============================

It's a Symfony2 bundle that integrates Select2 as a drop-in replacement for a standard entity field on a Symfony form.

2347PHP

Since Jun 26Pushed 10y agoCompare

[ Source](https://github.com/sharky98/select24entity-bundle)[ Packagist](https://packagist.org/packages/brunops/select24entity-bundle)[ RSS](/packages/brunops-select24entity-bundle/feed)WikiDiscussions master Synced 4w ago

READMEChangelogDependenciesVersions (1)Used By (0)

select24entity-bundle
=====================

[](#select24entity-bundle)

Fork description
----------------

[](#fork-description)

This bundle is a fork of the original [Select2Entity by Tetranz](https://github.com/tetranz/select2entity-bundle).

The goal of this fork is to modify the bundle to mimick Select2 behavior, meaning leaving the activation and the configuration of the field to the user in the javascript itself, at the exception of AJAX retrieval of the entities.

Introduction
------------

[](#introduction)

This is a Symfony2 bundle which enables the popular [Select2](https://select2.github.io) component to be used as a drop-in replacement for a standard entity field on a Symfony form.

The main feature that this bundle provides compared with the standard Symfony entity field (rendered with a html select) is that the list is retrieved via a remote ajax call. This means that the list can be of almost unlimited size. The only limitation is the performance of the database query or whatever that retrieves the data in the remote web service.

It works with both single and multiple selections. If the form is editing a Symfony entity then these modes correspond with many to one and many to many relationships. In multiple mode, most people find the Select2 user interface easier to use than a standard select tag with multiple=true with involves awkward use of the ctrl key etc.

The project was inspired by [lifo/typeahead-bundle](https://github.com/lifo101/typeahead-bundle) which uses the Typeahead component in Bootstrap 2 to provide similar functionality. Select24Entity can be used anywhere Select2 can be installed, including Bootstrap 3.

Thanks to @ismailbaskin we now have Select2 version 4 compatibility.

Screenshots
-----------

[](#screenshots)

This is a form with a single selection field list expanded.

[![Single select example](Resources/doc/img/single.png)](Resources/doc/img/single.png)

This is a form with a multiple selection field list expanded.

[![Multiple select example](Resources/doc/img/multi.png)](Resources/doc/img/multi.png)

Installation
------------

[](#installation)

Select2 must be installed and working first.

- select2.js, select2.css from
- If you want it integrated in bootstrap, select2-bootstrap.css from

These files live in the Resources/public/js and Resources/public/css folders of one of my bundles and then included in my main layout.html.twig file.

Alternatively, minified versions of select2.js and select2.css can be loaded from the CloudFlare CDN using the two lines of code given here: . Make sure the script tag comes after where jQuery is loaded. That might be in the page footer.

- Add `brunops/select24entity-bundle` to your projects `composer.json` "requires" section:

```
{
  // ...
  "require": {
    // ...
    "brunops/select24entity-bundle": "dev-master"
  }
}
```

Note that this only works with Select2 version 4.

- Run `php composer.phar update brunops/select24entity-bundle` in your project root.
- Update your project `app/AppKernel.php` file and add this bundle to the $bundles array:

```
$bundles = array(
  // ...
  new Brunops\Select24EntityBundle\BrunopsSelect24EntityBundle(),
);
```

- Update your project `app/config.yml` file to provide global twig form templates:

```
twig:
  form_themes:
    - 'BrunopsSelect24EntityBundle:Form:fields.html.twig'
```

- Load the Javascript on the page. The simplest way is to add the following to your layout file. Don't forget to run console assets:install. Alternatively, do something more sophisticated with Assetic.

```

```

How to use
----------

[](#how-to-use)

The following works on Symfony 2.8 (and probably Symfony 3, but not tested yet).

Select24Entity is simple to use. In the buildForm method of a form type class, specify `Select24EntityType::class` as the type where you would otherwise use `entity:class`.

Here's an example:

```
$builder
  ->add('country', Select24EntityType::class, [
    'multiple' => true,
    'remote_route' => 'brunops_test_default_countryquery',
    'class' => '\Brunops\TestBundle\Entity\Country',
    'primary_key' => 'id',
    'text_property' => 'name',
    'minimum_input_length' => 2,
    'page_limit' => 10,
    'allow_clear' => true,
    'delay' => 250,
    'cache' => true,
    'cache_timeout' => 60000, // if 'cache' is true
    'language' => 'en',
    'placeholder' => 'Select a country',
  ])
```

Put this at the top of the file with the form type class:

```
use Brunops\Select24EntityBundle\Form\Type\Select24EntityType;
```

In the template where you will use the field, you must activate it like you would with any Select2 field, using something like this:

```
$('.select24entity').select24entity();
```

Inside the parenthesis, you can pass any options that [Select2](https://select2.github.io/) can accept.

Options
-------

[](#options)

Defaults will be used for some if not set.

- `class` is your entity class. Required
- `primary_key` is the name of the property used to uniquely identify entities. Defaults to 'id'
- `text_property` This is the entity property used to retrieve the text for existing data. If text\_property is omitted then the entity is cast to a string. This requires it to have a \_\_toString() method.
- `multiple` True for multiple select (many to many). False for single (many to one) select.
- `minimum_input_length` is the number of keys you need to hit before the search will happen. Defaults to 2.
- `page_limit` This is passed as a query parameter to the remote call. It is intended to be used to limit size of the list returned. Defaults to 10.
- `allow_clear` True will cause Select2 to display a small x for clearing the value. Defaults to false.
- `delay` The delay in milliseconds after a keystroke before trigging another AJAX request. Defaults to 250 ms.
- `placeholder` Placeholder text.
- `language` i18n language code. Defaults to en.
- `cache` Enable AJAX cache. Results will be cached for each 'term' queried.
- `cache_timeout` How long to cache a query in milliseconds. Setting to `0` will cause the cache to never timeout *(60000 = 60 seconds)*
- `transformer` The fully qualified class name of a custom transformer if you need that flexibility as described below.

The url of the remote query can be given by either of two ways: `remote_route` is the Symfony route. `remote_params` can be optionally specified to provide parameters. Alternatively, `remote_path` can be used to specify the url directly.

The defaults can be changed in your app/config.yml file with the following format.

```
brunops_select24entity:
  minimum_input_length: 2
  page_limit: 8
  allow_clear: true
  delay: 500
  language: fr
  cache: false
  cache_timeout: 0
```

AJAX Response
-------------

[](#ajax-response)

The controller should return a `JSON` array in the following format. The properties must be `id` and `text`.

```
[
  { id: 1, text: 'Displayed Text 1' },
  { id: 2, text: 'Displayed Text 2' }
]
```

Select2 Taggable fields
-----------------------

[](#select2-taggable-fields)

If you want to use [Select2 Tags fields](https://select2.github.io/examples.html#tags), you need to do two things:

1. Activate the field with tags attribute to true:

```
$(".select24entity").select24entity({
  tags: true
});
```

2. Define a [Data Transformer](http://symfony.com/doc/2.8/cookbook/form/data_transformers.html) that act similar to this:

```
// Transform should return the same thing as the argument, Select24Entity will do the job.
public function transform($entities) {
  return $entities;
}

// This data transformer will receive the entities already parsed through the Select24Entity data transformer, alongside a key 'toCreate' if there is something to create.
public function reverseTransform($entities) {
  if ($entities->containsKey('toCreate')) {
    $toCreate = $entities->get('toCreate');
    $entities->remove('toCreate'); // We need to remove the key so that the Symfony Form component won't try to read it as if it was of same type of all other $entities
    // Simple loop to create the entities. Don't forget to persist them!
    foreach ($toCreate as $value) {
      if ($this->is_valid($value)) { // Some validation
        $newEntity = $this->createAndPersistEntity($value); // Create the entity object and persist it
        $entities->add($newEntity); // Add the entity to the ArrayCollection
      }
    }
  }
  return $entities;
}
```

\##Custom option text## If you need more flexibility in what you display as the text for each option, such as displaying the values of several fields from your entity or showing an image inside, you may define your own custom transformer. Your transformer must implement DataTransformerInterface. The easiest way is probably to extend EntityToPropertyTransformer or EntitiesToPropertyTransformer and redefine the transform() method. This way you can return as `text` anything you want, not just one entity property.

Here's an example that returns the country name and continent (two different properties in the Country entity):

```
$builder
  ->add('country', Select24EntityType::class, [
    'multiple' => true,
    'remote_route' => 'brunops_test_default_countryquery',
    'class' => '\Brunops\TestBundle\Entity\Country',
    'transformer' => '\Brunops\TestBundle\Form\DataTransformer\CountryEntitiesToPropertyTransformer',
  ]);
```

In transform sets data array like this:

```
$data[] = array(
  'id' => $country->getId(),
  'text' => $country->getName().' ('.$country->getContinent()->getName().')',
);
```

Your custom transformer and respectively your Ajax controller should return an array in the following format:

```
[
  { id: 1, text: 'United Kingdom (Europe)' },
  { id: 1, text: 'China (Asia)' }
]
```

\###Templating###

If you need [Templating](https://select2.github.io/examples.html#templating) in Select2, you could consider the following example that shows the country flag next to each option.

Your custom transformer should return data like this:

```
[
  { id: 1, text: 'United Kingdom (Europe)', img: 'images/flags/en.png' },
  { id: 2, text: 'China (Asia)', img: 'images/flags/ch.png' }
]
```

You need to define your own JavaScript function `select24entityAjax` which extends the original one `select24entity` and display custom template with image:

```
$.fn.select24entityAjax = function(action) {
  var action = action || {};
  var template = function (item) {
    var img = item.img || null;
    if (!img) {
      if (item.element && item.element.dataset.img) {
        img = item.element.dataset.img;
      } else {
        return item.text;
      }
    }
    return $(
      ' ' + item.text + ''
    );
  };
  this.select24entity($.extend(action, {
    templateResult: template,
    templateSelection: template
  }));
  return this;
};
$('.select2entity').select24entityAjax();
```

This script will add the functionality globally for all elements with class `select24entity`, but if the `img` is not passed it will work as the original `select24entity`.

You also will need to override the following block in your template:

```
{% block brunops_select24entity_widget_select_option %}

    {{ label.text }}

{% endblock %}
```

This block adds all additional data needed to the JavaScript function `select24entityAjax`, like data attribute. In this case we are passing `data-img`.

\##Embed Collection Forms## If you use [Embedded Collection Forms](http://symfony.com/doc/current/cookbook/form/form_collections.html) and [data-prototype](http://symfony.com/doc/current/cookbook/form/form_collections.html#allowing-new-tags-with-the-prototype) to add new elements in your form, you will need the following JavaScript that will listen for adding an element `.select24entity`:

```
$('body').on('click', '[data-prototype]', function(e) {
  $(this).prev().find('.select24entity').last().select24entity();
});
```

###  Health Score

24

—

LowBetter than 31% of packages

Maintenance20

Infrequent updates — may be unmaintained

Popularity15

Limited adoption so far

Community14

Small or concentrated contributor base

Maturity41

Maturing project, gaining track record

 Bus Factor2

2 contributors hold 50%+ of commits

How is this calculated?**Maintenance (25%)** — Last commit recency, latest release date, and issue-to-star ratio. Uses a 2-year decay window.

**Popularity (30%)** — Total and monthly downloads, GitHub stars, and forks. Logarithmic scaling prevents top-heavy scores.

**Community (15%)** — Contributors, dependents, forks, watchers, and maintainers. Measures real ecosystem engagement.

**Maturity (30%)** — Project age, version count, PHP version support, and release stability.

### Community

Maintainers

![](https://avatars.githubusercontent.com/u/8150191?v=4)[Sharky Suited](/maintainers/sharky98)[@sharky98](https://github.com/sharky98)

---

Top Contributors

[![tetranz](https://avatars.githubusercontent.com/u/2892757?v=4)](https://github.com/tetranz "tetranz (33 commits)")[![sharky98](https://avatars.githubusercontent.com/u/8150191?v=4)](https://github.com/sharky98 "sharky98 (19 commits)")[![tmisheva](https://avatars.githubusercontent.com/u/2970104?v=4)](https://github.com/tmisheva "tmisheva (11 commits)")[![lifo101](https://avatars.githubusercontent.com/u/367337?v=4)](https://github.com/lifo101 "lifo101 (3 commits)")[![Miljar](https://avatars.githubusercontent.com/u/472386?v=4)](https://github.com/Miljar "Miljar (2 commits)")[![mathieujamot](https://avatars.githubusercontent.com/u/10109558?v=4)](https://github.com/mathieujamot "mathieujamot (2 commits)")[![pivolan](https://avatars.githubusercontent.com/u/903550?v=4)](https://github.com/pivolan "pivolan (1 commits)")[![Chrisp1tv](https://avatars.githubusercontent.com/u/8688493?v=4)](https://github.com/Chrisp1tv "Chrisp1tv (1 commits)")[![kfi](https://avatars.githubusercontent.com/u/2392672?v=4)](https://github.com/kfi "kfi (1 commits)")[![jaimz22](https://avatars.githubusercontent.com/u/5921193?v=4)](https://github.com/jaimz22 "jaimz22 (1 commits)")

### Embed Badge

![Health badge](/badges/brunops-select24entity-bundle/health.svg)

```
[![Health](https://phpackages.com/badges/brunops-select24entity-bundle/health.svg)](https://phpackages.com/packages/brunops-select24entity-bundle)
```

###  Alternatives

[limenius/react-bundle

Client and Server-side react rendering in a Symfony Bundle

3861.2M](/packages/limenius-react-bundle)[area17/laravel-auto-head-tags

Laravel Auto Head Tags helps you build the list of head elements for your app

4616.0k](/packages/area17-laravel-auto-head-tags)[jelix/wikirenderer

WikiRenderer is a library to generate HTML or anything else from wiki content.

1712.2k1](/packages/jelix-wikirenderer)[webkinder/sproutset

A Composer package for handling responsive images in Roots Bedrock + Sage + Blade projects.

281.8k](/packages/webkinder-sproutset)

PHPackages © 2026

[Directory](/)[Categories](/categories)[Trending](/trending)[Changelog](/changelog)[Analyze](/analyze)
