Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Symfony2 Custom Form Field Type HTML5 color

I would like to add the HTML5 color input type (only supported by Chrome at the moment) within a Symfony2 form. I created a new color type which inherit from the text type :

<?php

namespace Marquis\WebsiteBundle\Form\Type;

use Symfony\Component\Form\AbstractType;

class ColorType extends AbstractType
{
    public function getParent()
    {
        return 'text';
    }

    public function getName()
    {
        return 'color';
    }
}

?>

and created a new service to use it :

marquis_website.form.type.color:
          class: Marquis\WebsiteBundle\Form\Type\ColorType
          tags:
              - { name: form.type, alias: color }

However, when the form is display, the input tag looks like this :

<input type="text" id="entity_hex" name="entity[hex]" value="#4D89BF">

So it's not using the new HTML5 color input but the text input.

Is there a way to override the type so it would display type="color"?

I also checked the fields.html.twig and there is this line which should works fine:

{% set type = type|default('text') %}

If i change default('text') to default('color'), all the input type="text" are change to type="color".

Thank you for your help,

like image 424
pjehan Avatar asked Nov 07 '13 20:11

pjehan


1 Answers

You also have to define new theme block for your field

{% form_theme form _self %}

{% block color_widget %}
{% spaceless %}
    {% set type = 'color' %}
    {{ block('form_widget_simple') }}
{% endspaceless %}
{% endblock %}

More about custom form fields

More about custom form themes

like image 90
adam187 Avatar answered Oct 19 '22 08:10

adam187