Posts tagged 'form'

Read-only Symfony form field

published on April 10, 2017.

The future me will be grateful for this post. I always get it wrong the first time.

To set a Symfony form field as a read-only, we can’t set the readonly attribute as an option on that field:

src/AppBundle/Form/FooType.php

<?php
declare(strict_types=1);

namespace AppBundle\Form;

use Symfony\Component\Form\AbstractType;
use Symfony\Component\Form\Extension\Core\Type\TextType;
use Symfony\Component\Form\FormBuilderInterface;

class FooType extends AbstractType
{
    public function buildForm(FormBuilderInterface $builder, array $options)
    {
        $builder->add('title', TextType::class, [
                'readonly' => true,
            ]);
    }
}

This won’t work, and will give the The option "readonly" does not exist. Defined options are:... exception.

We need to set it as an attribute of that field:

src/AppBundle/Form/FooType.php

<?php
declare(strict_types=1);

namespace AppBundle\Form;

use Symfony\Component\Form\AbstractType;
use Symfony\Component\Form\Extension\Core\Type\TextType;
use Symfony\Component\Form\FormBuilderInterface;

class FooType extends AbstractType
{
    public function buildForm(FormBuilderInterface $builder, array $options)
    {
        $builder->add('title', TextType::class, [
                'attr' => ['readonly' => true],
            ]);
    }
}

Happy hackin’!

Tags: php, symfony, form.
Categories: Programming, Development.

Playing with Zend Framework and Dojo

published on March 02, 2011.
Heads-up! You're reading an old post and the information in it is quite probably outdated.

Yesterday there was some talk on Twitter including Zend Framework and Dojo. I didn’t quite follow it through, something about why Dojo and not jQuery, it’s not that popular blablabla. Anyway, who cares? We have Zend_Dojo, we have ZendX_Jquery. I’m using ZendX_Jquery, but only as far as setting it up and loading jquery and jqueryui via the view helpers. Tried to use it on forms, to use tabs and whatnot, but in the end it was easier to write up a separate javascript file and do the jquery stuff there. But, I’ve never used Zend_Dojo before. Guess I was a bit scared away with all that dojo, dijit, dojox stuff… So, last night, being bored and all, I’ve decided to try and use it. Oh boy. How wrong was I for not diving into it before. OK, so far I’ve created only one form with dojo, but damn it’s good.

In short: set up the Zend_Dojo view helpers, pick a theme, make the forms extend Zend_Dojo_Form, change the elements from Zend_FormElement* to Zend_Dojo_FormElement*, if needed add/tweak some attributes and bang! the form is all sexy with nice colors & rounded borders & (error) messages in a nice little tooltip. And I haven’t wrote a single line of javascript. Not.a.single.line. Magic, I like it.

Setting it up

All I did was to set up dojo is:

<?php

class Bootstrap extends Zend_Application_Bootstrap_Bootstrap {

    public function _initViewHelpers()
    {
        $this->bootstrap('layout');
        $this->_layout = $this->getResource('layout');
        $this->_view = $this->_layout->getView();

        $this->_view->addHelperPath('Zend/Dojo/View/Helper','Zend_Dojo_View_Helper');

        $this->_view->dojo()
                        ->enable()
                        ->setCdnBase(Zend_Dojo::CDN_BASE_GOOGLE)
                        ->setCdnVersion('1.5.0')
                        ->setCdnDojoPath(Zend_Dojo::CDN_DOJO_PATH_GOOGLE)
                        ->addStyleSheetModule('dijit.themes.claro')
                        ->useCdn();
    }

and then just called echo $this->dojo(); in the layout and added class=“cairo” to the body element. I think this body thing can also be done via the helpers. The biggest struggle I had with the theme. Where do I download it? There’s no “download theme x” on the dojo website. How do I set it up? What is this madness? Then I realized it can pull not just the javascript files from the CDN, but also the CSS and images! Very cool.

A simple form

Next step: spice up the forms with Zend_Dojo_Form:

<?php
class My_Form extends Zend_Dojo_Form
{
    public function init()
    {
        $this->addElement(
            'ValidationTextBox',
            'title',
            array(
                'label' => 'Title:',
                'missingMessage' => 'You have to enter something', // overriding the default "This value is required."
                'promptMessage' => 'Enter a title', // on focus
                'invalidMessage' => 'Type some random characters, 3 min, 100 max', // error message for the failed regExp
                'regExp' => '.{3,100}', // regexp for validation
                'required' => true,
                'validators' => array(
                    array(
                        'validator' => 'StringLength', 'options' => array(3, 100)
                    )
                ),
                'filters' => array(
                    array(
                        'filter' => 'StringTrim',
                        'filter' => 'StripTags'
                    )
                )
            )
        );

With these ~20 lines I’ve got some basic client side validation with a pretty nice look and feel to it while still having all of the Zend_Form power to do the validation and filtering on the server side. Still need to figure out what those “constraints” are and how and for what to use them (they’re in the ZF manual, so they gotta be good for something), how to add for example a dojox.validate.isEmailAddress validator to the element, but for starters, this is quite impressive.

Besides this, I’ve also played with Zend_Dojo_Form_Element_Editor which is a WYSIWYG editor, extended Zend_Dojo_Form_Element_Button to create my own ResetButton (for some odd reason there is no reset button in Zend_Dojo), played around with the decorators… But that’s for some future rambling, gotta go to work now.

In the end, I feel stupid for not using Zend_Dojo before, well, Zend_Dojo_Form at least, but I definitely will be from now on. Here’s to hoping that it will be included in Zend Framework 2, too :)

Happy hackin’!

Tags: dojo, form, zend framework, zend_dojo, zf.
Categories: Programming.

Styling the default Zend_Form layout

published on December 22, 2008.
Heads-up! You're reading an old post and the information in it is quite probably outdated.

Here’s an example for styling Zend_Form’s default layout. The default layout is using definition lists. While there’s an option for changing the default layout, the wrapper tags and stuff, I see no reason for it. Create the form, add some CSS and your good to go :)

Note: Be sure to provide a Document Type in your view scripts like this:

<?php
<?= $this->doctype('XHTML1_STRICT') ?>

because when the form is generated, ZF is looking at the doctype to see how to create the form elements. Forgetting the doctype will probably generate invalid markup. I learned the hard way. Don’t do the same mistake, k? :)

The generated markup

So, here’s what Zend_Form makes for us (this markup is after submitting the form, but whit generated error, to show the error markup, too):

<form enctype="application/x-www-form-urlencoded" method="post" action="">
<dl class="zend_form">
    <dt>
        <label for="input1" class="required">Input field #1:</label>
    </dt>
    <dd>
        <input type="text" name="input1" id="input1" value="" />
        <ul class="errors">
            <li>Value is empty, but a non-empty value is required</li>
        </ul>
        <p class="description">Description? Yes, please.</p>
    </dd>
    <dt>
        &nbsp;
    </dt>
    <dd>
        <input type="submit" name="submit" id="submit" value="Submit form" />
    </dd>
</dl>
</form>

The PHP code which generates this form (without the error, of course) goes like this:

<?php
$input1 = new Zend_Form_Element_Text('input1');
$input1->setLabel('Input field #1:')
          ->setDescription('Description? Yes, please.')
          ->setRequired(true);

$submit = new Zend_Form_Element_Submit('submit');
$submit->setLabel('Submit form')

$form = new Zend_Form();
$form->setMethod('post')
       ->addElement($input1)
       ->addElement($submit);

Now, the generated form looks kinda good with no styling (which is good, if some maniac comes to visit with CSS support disabled).

OK, I lie: there’s a minimum of CSS for setting the background to white and the width to 460 pixels.

As you can see I’ve shortened the HTML and the PHP in the example codes…

The styling

I like my forms a bit different: form elements and their labels side by side with element descriptions and eventual errors showing up under the element. Here’s the CSS to achieve this:

.zend_form{
background:#fff;
width:460px;
margin:5px auto;
padding:0;
overflow:auto;
}

.zend_form dt{
padding:0;
clear:both;
width:30%;
float:left;
text-align:right;
margin:5px 5px 5px 0;
}

.zend_form dd{
padding:0;
float:left;
width:68%;
margin:5px 2px 5px 0;
}

.zend_form p{
padding:0;
margin:0;
}

.zend_form input, .zend_form textarea{
margin:0 0 2px 0;
padding:0;
}

.submit{
float:right;
}

.required:before{content:'* '}

.optional:before{content:'+ '}

Of course, this CSS takes care only of the layout; things like font types and sizes, colors, borders, backgrounds, etc. are not essential for this.

So, with this CSS applied to the generated Zend_Form, you can see on the image what will come up. And you know what’s the best part? It’s good for Firefox, Internet Explorer 6, Chrome and Opera, both under Windows and GNU/Linux (sorry, not tested for Internet Explorer 7 and Safari, but they should play along as well).

I almost forgot: I added a class=“submit” to the submit button, to be able to float it right. I first tried to do that with input[type=submit], but IE doesn’t know that, and as I wanted to make a styling that looks (almost) the same in all browsers with no hacks, I decided to add the class attribute.

So there, this little CSS code snippet should get you started with styling your Zend Form’s.

Cheers!

Robert Basic

Robert Basic

Software engineer, consultant, open source contributor.

Let's work together!

If you require outsourcing or consulting help on your projects, I'm available!

Robert Basic © 2008 — 2019
Get the feed