Category Archives: PHP - Page 6

Run simple php functions direct on command line

If you want to run/test oneliners in PHP on the command line you can use the -r option.

php -r 'echo "Hello World";' 

Will simply output “Hello World” on the command line

I sometimes use this method to test regexp expressions

php -r 'echo preg_match("/^Test/", "This is a test");'

Here I check if $string starts with the string ‘Test’ (the answer is no).

Using onliners on the command line can sometimes be very handy

Disable element or option in Zend_Form_Element

When disabling an element or option in a Zend_Form we use the function setAttrib() or, if multiple options, setAttribs(). These examples are made in Zend Framework 1.10

Disable a form element in the controller

$form = new Application_Form_MyForm();
$form->getElement('elementName')->setAttrib('disable', 'disable');

This will disable the whole ‘elementName’ element.

Disable option in a radio or select element
In declaration of element:

class Application_Form_MyForm extends Zend_Form {
...
        $typeOfLap = new Zend_Form_Element_Radio('elementName');
        $typeOfLap->setRequired(true)
                ->addMultiOptions(array(
                    'A' => 'Option A',
                    'B' => 'Option B'));
...
}

In controller

$form = new Application_Form_MyForm();
$form->getElement('elementName')->setAttrib('disable', array('A'));

This will disable option ‘Option A’. If you want to also disable ‘Option B’ you can add it to the disable array: array(‘A’, ‘B’). It works the same way with select elements

Set default radio button with Zend_Form_Element_Radio

Setting a default value (‘CHECKED’) in Zend_Form_Element_Radio is done with the function setValue(). This is an example of how to to this in Zend Framework 1.10

...
$typeOfLap = new Zend_Form_Element_Radio('typeoflap');
$typeOfLap->setRequired(true)
          ->addFilter('StripTags')
          ->addFilter('StringTrim')
          ->setDecorators(array('ViewHelper'))
          ->addMultiOptions(array(
               'Practice' => 'Practice',
               'Qualifying' => 'Qualifying'))
          ->setValue('Practice');
...

As most things in Zend this is also very simple.