Popular just now


How to Use Zend Framework 2 Forms in Another Script

I have been going back and forth on Zend Framework 2. First it helps me by providing some really robust code. The flip side of the coin is ZF2 makes me crazy because it's always explained terribly by classically educated computer scientist. Given that me and much of the PHP community are autodidacts this is a turn-off.

I always can tell how useful a PHP framework is by trying to do what I learned first in PHP, building a HTML form. Not one post or tutorial I could find gave a straight forward answer a to how things worked. What was worse no one gave working code for using ZF2 as a library used by another simple PH script. Trying to get this done simply and without Zends MVC in place seemed to be unattainable. This meant that ZF2 was not something I would use at first thought. That has changed now that I have this code working. This is a complete stand-alone class use of the Zend framework and only needs to be called.


         // finally send namespaces and prefixes to the autoloader SPL
 function zfform()

        // Zend Framework 2 form example

        $name = new Element('name');
        $name->setLabel('Your name');
            'type'  => 'text'

        $email = new Element\Email('email');
        $email->setLabel('Your email address');

        $subject = new Element('subject');
            'type'  => 'text'

        $message = new Element\Textarea('message');

        $captcha = new Element\Captcha('captcha');
        $captcha->setCaptcha(new Captcha\Dumb());
        $captcha->setLabel('Please verify you are human');

        $csrf = new Element\Csrf('security');

        $send = new Element('send');
            'type'  => 'submit'

        $form = new Form('contact');

        $nameInput = new Input('name');
        // configure input... and all others
        $inputFilter = new InputFilter();
        // attach all inputs


        $zfView = new \Zend\View\Renderer\PhpRenderer();
        $plugins = $zfView->getHelperPluginManager();
        $config  = new \Zend\Form\View\HelperConfig;

        $output = $zfView->form()->openTag($form) . "\n";
        $output .= $zfView->formRow($form->get('name')) . "
        $output .= $zfView->formRow($form->get('captcha')) . "
        $output .= $zfView->formSubmit( $form->get('send')) . "
        $output .= $zfView->form()->closeTag() . "\n";

        echo $output;

The above code will print out a HTML form when the Class method is called. I am using this class in the Content Connection Kit as an example of how to use it to blend third-party frameworks and CMS together as loosely coupled libraries.

No comments:

Post a Comment