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

Easier way to add an empty option in a select element #60

Closed
JorisDebonnet opened this issue Jul 15, 2015 · 39 comments
Closed

Easier way to add an empty option in a select element #60

JorisDebonnet opened this issue Jul 15, 2015 · 39 comments

Comments

@JorisDebonnet
Copy link

Continuing from this discussion, I believe it would be worthwhile to have an easier way to include an empty top option in a select field. It can be a pain to have to prepend it to a Collection manually (figuring out how to preserve keys) before passing it to Form::select, while I do believe this is a common use-case. Many dropdowns do not have anything selected by default, after all, so it would be nice if there were no hurdles to overcome to get this functionality.

What could be the best way to fix this? If not through a new option on Form::select, perhaps with a new built-in macro?

@adamgoose
Copy link
Member

Yeah, I like this idea. For now, you can do something like this:

  {!! Form::select('user_id', [null => 'Select a user...'] + $users->lists('name', 'id')) !!}

My idea for implementing this would be to add an option to the $attributes array you can pass in as the 4th argument, like so:

  {!! Form::select('user_id', $users->lists('name', 'id'), null, ['optional' => 'Select a user...']) !!}

Thoughts?

@Arkitecht
Copy link

I second the above. This would be the easiest, simplest implementation.

adamgoose added a commit that referenced this issue Jul 22, 2015
Signed-off-by: Adam Engebretson <adam@enge.me>
@adamgoose
Copy link
Member

Ok, I pushed something to master. Do you guys wanna play with it and see what you think?

@adamgoose
Copy link
Member

Docs here: http://laravelcollective.com/docs/master/html#drop-down-lists

Generating a Drop-Down List With an Empty Placeholder

echo Form::select('size', array('L' => 'Large', 'S' => 'Small'), null, ['optional' => 'Pick a size...']);

@JorisDebonnet
Copy link
Author

Works great!

I do personally wonder whether "optional" is the best label for it - why not simply "placeholder"? That word is not a valid attribute for a <select> tag in HTML4-5 anyway, so it would sort of be like "adding support" for it here. I also believe that the word "placeholder" makes more clear what it does than the word "optional".

@adamgoose
Copy link
Member

You know, I thought about that... But the placeholder attribute is actually not considered valid on a select element. I could call it placeholder and remove it from the $options before casting it to the dom attributes. I just wouldn't want to get it confused.

Thoughts anyone else? @tshafer?

@JorisDebonnet
Copy link
Author

Well, optional is not valid on a select element either, that's why I thought we could just as well make it something more recognizable :) It even makes some sense semantically (you never know they'll make it into a standard one day :o ).

But let's see what other people think.

@adamgoose
Copy link
Member

I am removing the "optional" attribute from the <select> element before I render it. See https://github.com/LaravelCollective/html/blob/master/src/FormBuilder.php#L500

@JorisDebonnet
Copy link
Author

Yeah I saw - I just mean you could handle placeholder the exact same way, as you suggested.

@JorisDebonnet
Copy link
Author

So what I mean is that it could make some sense being in between the other attributes in the $attributes array, even if it isn't "physically" an attribute.

@tshafer
Copy link
Contributor

tshafer commented Jul 22, 2015

I say we go with placeholder. I understand right away what this is supposed to do.

@adamgoose
Copy link
Member

Sounds good. I'll push the tweak now.

adamgoose added a commit that referenced this issue Jul 22, 2015
Signed-off-by: Adam Engebretson <adam@enge.me>
@rumeau
Copy link
Contributor

rumeau commented Jul 23, 2015

A placeholder shouldn't submit data, fb7693c renames the placeholder paramenter, but placeholder value is being sent for select element when placeholder item is selected.

@djtechonline
Copy link

Any update on this? I have an issue w/ moving a select element from a Laravel 5.0 project to Laravel 5.1 causing an Unsupported operand types error. Also, need to prepend multiple options such as:

{!! Form::select('user_selection',['' => '- select -'] + ['other'=>'Other (unlisted)'] + $data,null,['class'=>'form-control','placeholder'=>'Choose a value...']) !!}

Worked before, now it doesn't!
View more at: http://laravel.io/forum/08-03-2015-l51-unsupported-operand-types-error-on-select-element-w-default-blank-dropdown-option

@JorisDebonnet
Copy link
Author

Try using $data.toArray().

@djtechonline
Copy link

I tried your .toArray() suggestion, but I still get the same error.

@azulkipli
Copy link

I tried on laravel 5.1

{!! Form::select('size', array('L' => 'Large', 'S' => 'Small'), null, ['placeholder' => 'Pick a size...']) !!}

Not work

@tshafer
Copy link
Contributor

tshafer commented Aug 15, 2015

What error did you get if any?

@ghost
Copy link

ghost commented Aug 16, 2015

@tshafer I'm having the same problem - there's no error message, but no placeholder <option> either. It renders the following:

<select name="size" placeholder="Pick a size...">
  <option value="L">Large</option>
  <option value="S">Small</option>
</select>

Laravel 5.1

@adamgoose
Copy link
Member

Could you both do me a favor, and run composer show --installed inside your Laravel application, and get me the version and commit hash of the laravelcollective/html you have installed?

@adamgoose adamgoose reopened this Aug 16, 2015
@azulkipli
Copy link

anahkiasen/underscore-php             2.0.0              A redacted port of Underscore.js for PHP
barryvdh/elfinder-builds              v2.1.0.5           File manager for web
barryvdh/elfinder-flysystem-driver    v0.1.1             A Flysystem Driver for elFinder
barryvdh/laravel-debugbar             v2.0.5             PHP Debugbar integration for Laravel
barryvdh/laravel-elfinder             v0.3.4             A Laravel Package to integrate elFinder 2
barryvdh/laravel-ide-helper           v2.1.0             Laravel IDE Helper, generates correct PHPDocs for all Facade classes, to improve auto-completion.
baum/baum                             1.1.1              Baum is an implementation of the Nested Set pattern for Eloquent models.
classpreloader/classpreloader         2.0.0              Helps class loading performance by generating a single PHP file containing all of the autoloaded files for a specific use case
creativeorange/gravatar               v1.0.5             A Laravel 5.0 & 5.1 gravatar package for retrieving gravatar image URLs or checking the existance of an image.
danielstjules/stringy                 1.9.0              A string manipulation library with multibyte support
dnoegel/php-xdg-base-dir              0.1                implementation of xdg base directory specification for php
doctrine/cache                        v1.4.1             Caching library offering an object-oriented API for many cache backends
doctrine/inflector                    v1.0.1             Common String Manipulations with regard to casing and singular/plural rules.
doctrine/instantiator                 1.0.5              A small, lightweight utility to instantiate objects in PHP without invoking their constructors
fortawesome/font-awesome              v4.4.0             The iconic font and CSS framework
fzaninotto/faker                      v1.5.0             Faker is a PHP library that generates fake data for you.
graham-campbell/manager               v2.2.0             Manager Provides Some Manager Functionality For Laravel 5
greggilbert/recaptcha                 dev-master 7d77a6d reCAPTCHA Validator for Laravel 5
guzzle/guzzle                         v3.9.3             PHP HTTP client. This library is deprecated in favor of https://packagist.org/packages/guzzlehttp/guzzle
guzzlehttp/cache-subscriber           0.1.0              Guzzle HTTP cache subscriber
guzzlehttp/guzzle                     5.3.0              Guzzle is a PHP HTTP client library and framework for building RESTful web service clients
guzzlehttp/log-subscriber             1.0.1              Logs HTTP requests and responses as they are sent over the wire (Guzzle 4+)
guzzlehttp/psr7                       1.1.0              PSR-7 message implementation
guzzlehttp/retry-subscriber           2.0.2              Retries failed HTTP requests using customizable retry strategies (Guzzle 4+)
guzzlehttp/ringphp                    1.1.0              Provides a simple API and specification that abstracts away the details of HTTP into a single PHP function.
guzzlehttp/streams                    3.0.0              Provides a simple abstraction over streams of data
hamcrest/hamcrest-php                 v1.2.2             This is the PHP port of Hamcrest Matchers
hashids/hashids                       1.0.5              Generate hashids like YouTube or Bitly from numbers to obfuscate your database primary ids, or navigate to the right shard.
hieu-le/active                        2.2.1              The helper class for Laravel 4 applications to get active class base on current route
illuminate/html                       v5.0.0             
intervention/image                    2.3.1              Image handling and manipulation library with support for Laravel integration
jakub-onderka/php-console-color       0.1                
jakub-onderka/php-console-highlighter v0.3.2             
jenssegers/date                       v3.0.7             A date library to help you work with dates in different languages
jeremeamia/SuperClosure               2.1.0              Serialize Closure objects, including their context and binding
laracasts/generators                  1.1.1              Extend Laravel 5's generators.
laracasts/utilities                   2.0                Transform your PHP to JavaScript
laradic/support                       1.2.8              Laravel support package
laravel/framework                     v5.1.10            The Laravel Framework.
laravel/socialite                     v2.0.10            Laravel wrapper around OAuth 1 & OAuth 2 libraries.
laravelcollective/html                v5.1.4             
laravelcollective/remote              v5.1.0             Remote for The Laravel Framework.
league/flysystem                      1.0.11             Filesystem abstraction: Many filesystems, one API.
league/fractal                        0.12.0             Handle the output of complex data structures ready for API output.
league/glide                          0.3.5              Wonderfully easy on-demand image manipulation library with an HTTP based API.
league/oauth1-client                  1.5.0              OAuth 1.0 Client Library
maximebf/debugbar                     v1.10.4            Debug bar in the browser for php application
michelf/php-markdown                  1.4.1              PHP Markdown
mockery/mockery                       0.9.4              Mockery is a simple yet flexible PHP mock object framework for use in unit testing with PHPUnit, PHPSpec or any other testing framework. Its...
monolog/monolog                       1.16.0             Sends your logs to files, sockets, inboxes, databases and various web services
mtdowling/cron-expression             v1.0.4             CRON for PHP: Calculate the next or previous run date and determine if a CRON expression is due
namshi/jose                           5.0.2              JSON Object Signing and Encryption library for PHP.
nesbot/carbon                         1.20.0             A simple API extension for DateTime.
nikic/php-parser                      v1.4.0             A PHP parser written in PHP
patchwork/utf8                        v1.2.3             Portable and performant UTF-8, Unicode and Grapheme Clusters for PHP
php-tmdb/api                          v2.0.10            PHP wrapper for TMDB (TheMovieDatabase) API v3. Supports two types of approaches, one modelled with repositories, models and factories. And ...
php-tmdb/laravel                      v1.0.2             Laravel Package for TMDB ( The Movie Database ) API. Provides easy access to the wtfzdotnet/php-tmdb-api library.
phpdocumentor/reflection-docblock     2.0.4              
phpseclib/phpseclib                   0.3.10             PHP Secure Communications Library - Pure-PHP implementations of RSA, AES, SSH2, SFTP, X.509 etc.
phpspec/php-diff                      v1.0.2             A comprehensive library for generating differences between two hashable objects (strings or arrays).
phpspec/phpspec                       2.2.1              Specification-oriented BDD framework for PHP 5.3+
phpspec/prophecy                      v1.5.0             Highly opinionated mocking framework for PHP 5.3+
phpunit/php-code-coverage             2.2.2              Library that provides collection, processing, and rendering functionality for PHP code coverage information.
phpunit/php-file-iterator             1.4.1              FilterIterator implementation that filters files based on a list of suffixes.
phpunit/php-text-template             1.2.1              Simple template engine.
phpunit/php-timer                     1.0.7              Utility class for timing
phpunit/php-token-stream              1.4.5              Wrapper around PHP's tokenizer extension.
phpunit/phpunit                       4.8.3              The PHP Unit Testing framework.
phpunit/phpunit-mock-objects          2.3.6              Mock Object library for PHPUnit
psr/http-message                      1.0                Common interface for HTTP messages
psr/log                               1.0.0              Common interface for logging libraries
psy/psysh                             v0.5.2             An interactive shell for modern PHP.
radic/blade-extensions                4.1.1              Laravel package providing additional Blade extensions: foreach (with $loop data like twig), break, continue, set,array (multiline), etc
radic/tmp-underscore-php              1.3.2              Temporary package until underscore-php updates its dependencies. A redacted port of Underscore.js for PHP
react/promise                         v2.2.1             A lightweight implementation of CommonJS Promises/A for PHP
rtconner/laravel-tagging              1.1.3              Use PHP traits to extend Laravel Eloquent Models to allow Tags. Models can be marked as Taggable.
sebastian/comparator                  1.2.0              Provides the functionality to compare PHP values for equality
sebastian/diff                        1.3.0              Diff implementation
sebastian/environment                 1.3.2              Provides functionality to handle HHVM/PHP environments
sebastian/exporter                    1.2.1              Provides the functionality to export PHP variables for visualization
sebastian/global-state                1.0.0              Snapshotting of global state
sebastian/recursion-context           1.0.1              Provides functionality to recursively process PHP variables
sebastian/version                     1.0.6              Library that helps with managing the version number of Git-hosted PHP projects
spatie/eloquent-sortable              1.1.2              Sortable behaviour for eloquent models
spatie/laravel-glide                  2.2.5              A Glide Service Provider for Laravel
spatie/laravel-medialibrary           3.1.3              Associate files with Eloquent models
spatie/laravel-responsecache          1.1.4              Speed up a Laravel application by caching the entire response
spatie/pdf-to-image                   1.0.1              Convert a pdf to an image
spatie/string                         2.0.0              String handling evolved
stripe/stripe-php                     v1.18.0            Stripe PHP Library
swiftmailer/swiftmailer               v5.4.1             Swiftmailer, free feature-rich PHP mailer
symfony/class-loader                  v2.7.3             Symfony ClassLoader Component
symfony/console                       v2.7.3             Symfony Console Component
symfony/css-selector                  v2.7.3             Symfony CssSelector Component
symfony/debug                         v2.7.3             Symfony Debug Component
symfony/dom-crawler                   v2.7.3             Symfony DomCrawler Component
symfony/event-dispatcher              v2.7.3             Symfony EventDispatcher Component
symfony/filesystem                    v2.7.3             Symfony Filesystem Component
symfony/finder                        v2.7.3             Symfony Finder Component
symfony/http-foundation               v2.7.3             Symfony HttpFoundation Component
symfony/http-kernel                   v2.7.3             Symfony HttpKernel Component
symfony/options-resolver              v2.7.3             Symfony OptionsResolver Component
symfony/process                       v2.7.3             Symfony Process Component
symfony/routing                       v2.7.3             Symfony Routing Component
symfony/translation                   v2.7.3             Symfony Translation Component
symfony/var-dumper                    v2.7.3             Symfony mechanism for exploring and dumping PHP variables
symfony/yaml                          v2.7.3             Symfony Yaml Component
twbs/bootstrap                        v3.3.5             The most popular front-end framework for developing responsive, mobile first projects on the web.
twbs/bootstrap-sass                   v3.3.5             bootstrap-sass is a Sass-powered version of Bootstrap, ready to drop right into your Sass powered applications.
tymon/jwt-auth                        0.5.4              JSON Web Token Authentication for Laravel 4 and 5
uxweb/sweet-alert                     1.1.1              A simple PHP package to show Sweet Alerts with the Laravel Framework
vinelab/laravel-editor                v1.0.3             Markdown Text Editor (WYSIWYG) with social network embeds support and a nifty json output.
vinkla/hashids                        1.1.0              Laravel 5 wrapper for the Hashids API.
vlucas/phpdotenv                      v1.1.1             Loads environment variables from `.env` to `getenv()`, `$_ENV` and `$_SERVER` automagically.
webmozart/path-util                   1.1.0              A robust cross-platform utility for normalizing, comparing and modifying file paths.
yajra/laravel-datatables-oracle       v5.11.0            jQuery DataTables API for Laravel 4|5

@adamgoose
Copy link
Member

Looks like you have laravelcollective/html v5.0.0 installed. Please update your composer.json file and use version 5.1.*.

Thanks,
Adam.

@adamgoose
Copy link
Member

Oh, just kidding. Looks like you do have laravelcollective/html v5.1.* installed, however you also have illuminate/html v5.0.0 installed. This is surely what is causing your troubles.

@nancymic2
Copy link

Hi
I have been looking for a way to let a user select a value or no value at all or even some sentinel value (since the values are coming from the companies table and may not want to associate an expense with any company) but no matter what i use here, empty string, NULL, zeros, I don't think this value is getting passed in the update statement. Is it? Can it?
{{ Form::select('company_id', [null => '000000'] + $company1_lists) }}

@adamgoose
Copy link
Member

@nancymic2
Copy link

@adamgoose
Thanks much. From above, the select dropdown works, but I guess my issue is that I don't know how to add a value to the array or collection or whatever is coming from the database using lists and have it sent as the company id value back to the database on submit

@adamgoose
Copy link
Member

If $companies is an instance of the Laravel Collection class, you can call $companies->lists('name', 'id')

@nancymic2
Copy link

Thanks I'll take a look

@nancymic2
Copy link

FYI $companies is a table
duh. I think it's json

@godbout
Copy link

godbout commented Aug 3, 2016

Quick question. When I use the placeholder, I end up with an empty field in my request::all() data if the user chooses that option. The problem is that the field has a foreign key, and although it can be null, it cannot be equal to an empty string. So is the way to deal with that is to add an null => 'Choose blablal' in front of my array of options, or there is something that I don't understand with the placeholder, like how to set a default value? Hope that make sense. Thanks!

@justinexoplanet
Copy link

For me, doing Form::select('size', ['L' => 'Large', 'S' => 'Small'], null, ['placeholder' => 'Pick a size...']);
when I'm updating a form, it passes "Pick a size..." when submitted on update. That's not what it should do.

Is there any fix for passing an empty field yet?

@robertholf
Copy link

https://laravelcollective.com/docs/master/html#drop-down-lists
echo Form::select('size', ['L' => 'Large', 'S' => 'Small'], null, ['placeholder' => 'Pick a size...']);
or in my example with a binded model
{{ Form::select('size', $sizes, null, ['class' => 'form-control', 'placeholder' => 'Select a Size...']) }}

@octoxan
Copy link

octoxan commented Dec 19, 2016

So there's no method of adding an extra option at the top, and not pre-selecting it? I have a bunch of data and for each row in the database there's a page with a form on it to modify it. I'd like to have the current value be the default selected option, but adding a placeholder overrides this. =/

@robertholf
Copy link

robertholf commented Dec 19, 2016

@octoxan the "null" value in can be used to specify the selected option. The placeholder will just add a dummy value at the top and will be selected if the 3rd argument is null.

Default selected:
{{ Form::select('size', $sizes, null, ['class' => 'form-control', 'placeholder' => 'Select a Size...']) }}

Specific Value Selected:
{{ Form::select('size', $sizes, $data->size, ['class' => 'form-control', 'placeholder' => 'Select a Size...']) }}

*$data is the current record and size is the related field
*$sizes is an object with all options

@octoxan
Copy link

octoxan commented Dec 19, 2016

@robertholf Weird, I swear I tried that right before I posted and it was still selecting the placeholder. Works now though. lol

@Ghafoorfahim
Copy link

Ghafoorfahim commented Mar 29, 2018

@JorisDebonnet
I think its the easy and the best way.
{{Form::select('diameter',$diameter,null,['class' => 'form-control','placeholder' => 'Select diameter'])}}

@palakvasani
Copy link

Hello,
I am facing this same issue? Can I refer anywhere for this resolution please?
Regards,
Palak

@robertholf
Copy link

@palakvasani check my response above

@AmazingVanish
Copy link

This is working well for me, however it is common practice to add the "disabled" attribute on the option so it is evident (dimmed) when clicking on it that the option is not acceptable. Would it be possible to add that, or would it cause problems for people who need the empty to be returned?

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

No branches or pull requests