Ярлыки

.htaccess (4) тестирование (8) шаблоны проектирования (3) css (5) Debian (6) docker (2) Doctrine2 (6) Git (6) html (4) java (6) javascript (13) jquery (11) LFS (3) linux (23) mac os (4) mod_rewrite (2) MSSQL (4) MySQL (18) ORM Doctrine (17) patterns (3) PDO (3) perl (7) PHP (64) PHPUnit (8) Python (15) SEO (2) Silex (1) SimpleXML (1) SQL (14) ssh (4) Ubuntu (24) Yii1 (1) Zend Framework (19) ZendFramework2 (8)

пятница, 23 марта 2012 г.

Zend Framework. Композитный элемент формы на примере номера телефона.

Объект элемента формы 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);
...

Комментариев нет:

Отправить комментарий