(using Zend 1.11.11)
So I wanted to make a phone number input that would have 3 boxes; area code, prefix and line. (Yes I just now learned what the three parts meant)
To do this, you need to create two things:
- A Form Element
-
- This is used to validate our element.
- A View Helper to display it.
-
- Used to create the input boxes.
Here is my PhoneNumber class:
setValue($value); // Parent call to isValid will set the value to a single part, not the whole phone number.
return false;
}
// If the user entered a number, make sure that the values are digits.
if($value != null){
// Make sure that each fild is a number
$digits = new Zend_Validate_Digits();
$errors = array();
if(!$digits->isValid($area) || !$digits->isValid($prefix) || !$digits->isValid($line)){
$this->setValue($value); // $digits->isValid will set the value to either $area, $prefix or $line, which is not the phone number value.
$this->_messages = array('Please only use numbers for phone number.');
$this->markAsError();
return false;
}
}
// Parent resets the value.
$this->setValue($value);
return true;
}
public function getValue()
{
if(is_array($this->_value)) {
$value = $this->_value['area'] . '-' .
$this->_value['prefix'] . '-' .
$this->_value['line'];
// No value given.
if($value == '--') {
$value = null;
}
$this->setValue($value);
}
return parent::getValue();
}
}
The class is pretty straight forward; it has two methods, getValue and isValid. isValid does the following:
- Creates a phone number value of xxx-xxx-xxxx.
- Uses parent isValid method to check for blank values (if required)
- Checks each part of the phone number to see if only numbers were used.
getValue() just returns the xxx-xxx-xxxx format of the phone number.
Now we need a way to create the actual display of our new element, this is where our view helper comes in:
view->formText(
$name . '[area]',
$area,
$areaAttribs) . '-' .
$this->view->formText(
$name . '[prefix]',
$prefix,
$prefixAttribs) . '-' .
$this->view->formText(
$name . '[line]',
$line,
$lineAttribs
);
}
}
This view helper creates 3 textboxes (using FormText view helper) to create the phone number element.
To add the element to a form:
$this->addElement('phoneNumber', 'phone_number', array(
'label' => 'Phone Number',
'validators' => array(
array('NotEmpty', true, array('messages' => 'Please input your phone number.'))
),
'required' => true,
'class' => 'phonenumber'
));
Over all, that’s pretty simple. You could use decorators (which I made a post about in one of my first blog postings Creating A Dynamic Grouped Form Element) but that seems to be a little bit more complicated, but I think it does provide more power…
Any way, with this approach you can start building some complex inputs fairly easily.