12/06/09

ZF 1.8 Zend_Form automatically sets form encoding on upload

As of ZF 1.8 Zend_Form’s enctype defaults to multipart when a file element is attached. Prior to this version you have to do this manually like so:

$form->setAttrib('enctype', 'multipart/form-data');
//or
$form->setAttrib('enctype', Zend_Form::ENCTYPE_MULTIPART);

More info on Zend_Form_Element_File

05/02/09

The past months useful links

Lots has been going on since last my post. I’ve been awful busy and could find no time to commit to regular posts or any for that matter so I’ll start with some useful links and try to post more often.

Zend Framework

We’ve seen the release of 1.7.0 and since four mini releases bringing us up to Zend Framework 1.7.4. I’ll cover some of the new features and improvements later.

There has been a great deal discussion in the ZF community on the Model in Model-View-Controller pattern, this prompted many blog posts including Matthew Weier O’Phinneys series of posts Using Zend_Form in Your Models, Applying ACLs to Models, Model Infrastructure, Padraic Bradys The M in MVC: Why Models are Misunderstood and Unappreciated and last but not least Rob Allens On models in a Zend Framework application.

Pádraic Brady launched his online book Zend Framework: Surviving the Deep End and has since posted three chapters and an invaluable Appendix on Performance Optimisation.

Eclipse PDT 2.0

PDT 2.0 has been released, you can download it if you haven’t already from eclispe.org or zend.com.

Webinar: Introduction to Eclipse PHP Development Tools (PDT) 2.0

Roy Ganor, Zend Studio Project Leader at Zend demonstrates PDT 2.0’s new features including creating a new project, source editing, code assist, type hierarchy, mark occurrences, PHP search and more.

I’ll cover some of the new features and some tips & tricks for new users later.

Internet Explorer 8

It’s on its way and like Chitty Chitty Bang Bang it has all the bells and whistles you could want. It promises full CSS 2.1 support which is fair enough, sadly most of the magic of CSS3 will be lost on IE8.

If you want to follow the release of this the IEBlog is good place to start.

IE 8 RC1 is now available

Firefox

Very recently sitepoint announced the release of firescope, a new add-on for Firebug, the popular web development tool, that extends it with reference material for HTML and CSS.

This is very usefull add-on.

There’s been lots more going on, but that’s all for now, enjoy!

17/11/08

Zend Framework 1.7.0 is now available!

Almost three hundred bugs fixed and many welcome additions, one of which is the new Performance Guide in the reference manual.

1.7.0 can  be downloaded from the Zend Framework download site.

Well done ZF Team!

10/11/08

Zend_Dojo_Form and Form Validation on the Client Side

One thing those of you who have been using Zend_Dojo_Form might have noticed is that dojo enabled forms don’t show validation warnings when submitted i.e. when the submit button is clicked. This can be quite confusing for the end user.

So, how do we get our dojo enabled forms to validate when submitted?

Matthew Weier O’Phinney explains on nabble that:

You need to bind to the onSubmit event of your form, and validate in
your callback. One way to do this is as follows, from your view script:

< ? $this->dojo()->javascriptCaptureStart() ?>
function validateForm() {
    var form = dijit.byId("<formid>");
    if (!form.validate()) {
        alert("Invalid form");
        return false;
    }
    return true;
}
< ? $this->dojo()->javascriptCaptureEnd() ?>
< ? $this->dojo()->onLoadCaptureStart() ?>
function () {
    dojo.connect(dijit.byId("</formid><formid>"), "onSubmit", "validateForm");
}
< ? $this->dojo()->onLoadCaptureEnd() ?>
</formid>

What the above does is connect the onSubmit event to the form, which
then executes the validateForm() function; if this returns false,
submission is halted, and, in this case, an alert raised. You could also
popup a dialog box or some other notification.

The above snippet of code Matthew describes doesn’t quite work. An Issue has been created for it here http://framework.zend.com/issues/browse/ZF-4587, but there is a work around, we can use headScript()->capture instead.

Let’s look at how to apply this as a view helper.

The view helper:

library/My/View/Helper/ValidateDojoForm.php

class My_View_Helper_ValidateDojoForm extends Zend_View_Helper_Abstract
{
    public $view;
 
    public function setView(Zend_View_Interface $view)
    {
        $this->view = $view;
    }
 
    /**
     * Validate dojo enabled form onSubmit.
     *
     * @param  string $formId
     * @return void
     */
    public function ValidateDojoForm($formId)
    {
        $this->view->headScript()->captureStart(); ?>
        function validateForm() {
            var form = dijit.byId("< ?php echo $formId; ?>");
            if (!form.validate()) {
                return false;
            }
            return true;
        }
        dojo.addOnLoad(function () {
            dojo.connect(dijit.byId("< ?php echo $formId; ?>"), "onSubmit", "validateForm");
        });
        < ?php $this->view->headScript()->captureEnd();
    }
}

This is very simple view helper. All you need to do is call validateDojoForm in your view script passing in the id of the form you want to be validated on submission as follows:

$this->validateDojoForm('formId');

Helper paths need set up, one way of doing this is in our bootstrap as follows:

/**
 * Initialize view and layouts
 */
$layout = Zend_Layout::startMvc('/path/to/layouts');
$view = $layout->getView()
    ->addHelperPath('My/View/Helper/', 'My_View_Helper')
    ->addHelperPath('Zend/Dojo/View/Helper/', 'Zend_Dojo_View_Helper');

More information on view helpers and helper paths.

What about a custom class that does all the work for us?

A Custom Zend Dojo Form Class

library/My/Dojo/Form.php

class My_Dojo_Form extends Zend_Dojo_Form
{
    /**
     * Set form name
     *
     * @param  string $name
     * @return Zend_Form
     */
    public function setName($name)
    {
        parent::setName($name);
        $this->getView()->validateDojoForm($this->getName());
        return $this;
    }
}

All this does is call our validateDojoForm helper and pass it the id of the form we create. Now we create all our Dojo forms by extending our custom class:

class Form_Name extends My_Dojo_Form
{
    public function init()
    {
        $this->setName('myForm');
 
        $this->addElement('ValidationTextBox', 'name', array(
            'validators' => array(
                array('StringLength', false, array(0, 255)),
            ),
            'label'          => 'Name',
            'required'       => true,
            'invalidMessage' => 'Please type your name.',
            'trim'      => true,
        ));
 
 
        $this->addElement('SubmitButton', 'submitButton',
            array(
                'required'   => false,
                'ignore'     => true,
                'label'      => 'Save'
            )
        );
    }
}

Be sure to call setName() when creating your form. This will call our validateDojoForm helper and pass it the id of the form we create and thus capturing the neccessary javascript to validate our form when it’s submitted.

enjoy!

02/09/08

Zend framework: Logging Database Queries to FireBug

Logging database queries to FireBug is sinfully simple with the new component Zend_Db_Profiler_Firebug in ZF 1.6, now available, you can download it here Zend Framework Download Page.

Requirements:

  1. Firefox Browser ideally version 3 but version 2 is also supported.
  2. Firebug Firefox Extension.
  3. FirePHP Firefox Extension.

More information on requirements at the Zend Framework Documentation -  Profiling with Firebug

Let’s look at some examples.

< ?php
// Instatiate the database
$db = Zend_Db::factory('Pdo_Mysql',
    array(
        'host' => 'localhost',
        'dbname' => 'zf_feature_testing',
        'username' => 'user123',
        'password' => 'pass123'
    )
);
 
// Instantiate the profiler in your bootstrap file 
$profiler = new Zend_Db_Profiler_Firebug('All Database Queries:');
// Enable it
$profiler->setEnabled(true);
// Attach the profiler to your db adapter 
$db->setProfiler($profiler);
 
// Run your queries
$result1 = $db->fetchAll('SELECT * FROM zf_test');
$result2 = $db->fetchAll('SELECT * FROM zf_test where id = ?', 3);

Alternatively you can add the profiler parameters to the Zend_Db factory.

< ?php
// Instatiate the database, passing in the profiler parameters.
$db = Zend_Db::factory('Pdo_Mysql',
    array(
        'host' => 'localhost',
        'dbname' => 'zf_feature_testing',
        'username' => 'user123',
        'password' => 'pass123',
        'profiler' => array(
            'enabled' => true,
            'class' => 'Zend_Db_Profiler_Firebug'
        )
    )
);

Or from an .ini file using Zend_Config_Ini

$config = new Zend_Config_Ini('../application/config.ini', 'development');
$db = Zend_Db::factory($config->database);

config.ini

[development]
database.adapter                    = pdo_mysql
database.params.host                = localhost
database.params.username            = user123
database.params.password            = pass123
database.params.dbname              = zf_feature_testing
database.params.profiler.enabled    = true
database.params.profiler.class      = Zend_Db_Profiler_Firebug

Show me my profiling data?

Open FireBug, you will see a link under console.

Profiling with FireBug

Click it open and it will list all the queries that were run.

Profiling with FireBug

Enjoy!