Объект элемента формы library/App/Form/Element/Phone.php
class App_Form_Element_Phone extends Zend_Form_Element_Xhtml {
public $helper = 'phoneElement';
protected $countryCode;
protected $providerCode;
protected $number;
public function setCountryCode($num) {
$this->countryCode = $this->filter($num);
return $this;
}
public function setProviderCode($num) {
$this->providerCode = $this->filter($num);
return $this;
}
public function setNumber($num) {
$this->number = $this->filter($num);
return $this;
}
// Примитивная фильтрация данных, вырезаем все кроме цифр
protected function filter($num) {
return preg_replace('/[^\d]/', '', $num);
}
public function __construct($spec, $options = null) {
parent::__construct($spec, $options);
// Можно не удалять
$this->removeDecorator('HtmlTag');
}
public function setValue($value) {
if (is_array($value) && isset($value['country_code'],
$value['provider_code'], $value['number'])) {
$this->setCountryCode($value['country_code'])
->setProviderCode($value['provider_code'])
->setNumber($value['number']);
}
}
public function getValue() {
if(! $this->countryCode || ! $this->providerCode
|| ! $this->number)
return false; // Благодаря этому срабатывает валидатор NotEmpty
return array(
'country_code' => $this->countryCode,
'provider_code' => $this->providerCode,
'number' => $this->number
);
}
}
Помощник вида для элемента library/App/View/Helper/PhoneElement.php
class App_View_Helper_PhoneElement extends Zend_View_Helper_FormElement {
protected $html = '';
public function phoneElement($name, $value = null, $attribs = null) {
$providerCode = $countryCode = $number = '';
// Формирует элемент html - текстовое поле,
// стандартный помощник вида
$helper = new Zend_View_Helper_FormText();
$helper->setView($this->view);
$countryCode = isset($value['country_code'])
? $value['country_code'] : '7';
$providerCode = isset($value['provider_code'])
? $value['provider_code'] : '';
$number = isset($value['number'])
? $value['number'] : '';
// Формируем html-код элемента
$this->html .= '<div class="phone-plus">+</div>'
. $helper->formText($name
. '[country_code]', $countryCode, array('size' => 3,
'maxlength' => 3));
$this->html .= $helper->formText($name
. '[provider_code]', $providerCode, array('size' => 5,
'maxlength' => 5));
$this->html .= $helper->formText($name
. '[number]', $number, array('size' => 7, 'maxlength' => 7));
$this->html .= '<div class="clear"></div>';
return $this->html;
}
}
Применение элемента в форме
...
$phone = new App_Form_Element_Phone('phone');
$phone->setLabel('Телефон +7(XXX)XXXXXXX')->setRequired();
$phone->addValidator('NotEmpty', true, array(
'messages' => array('isEmpty' => 'Необходимо ввести номер телефона')));
$this->addElement($phone);
...
Комментариев нет:
Отправить комментарий