Webylon 3.1 API Docs
  • Package
  • Class
  • Tree
  • Deprecated
  • Download
Version: current
  • 3.2
  • 3.1

Packages

  • auth
  • Booking
  • cart
    • shipping
    • steppedcheckout
  • Catalog
  • cms
    • assets
    • batchaction
    • batchactions
    • bulkloading
    • comments
    • content
    • core
    • export
    • newsletter
    • publishers
    • reports
    • security
    • tasks
  • Dashboard
  • DataObjectManager
  • event
  • faq
  • forms
    • actions
    • core
    • fields-basic
    • fields-dataless
    • fields-datetime
    • fields-files
    • fields-formatted
    • fields-formattedinput
    • fields-relational
    • fields-structural
    • transformations
    • validators
  • googlesitemaps
  • guestbook
  • installer
  • newsletter
  • None
  • photo
    • gallery
  • PHP
  • polls
  • recaptcha
  • sapphire
    • api
    • bulkloading
    • control
    • core
    • cron
    • dev
    • email
    • fields-formattedinput
    • filesystem
    • formatters
    • forms
    • i18n
    • integration
    • misc
    • model
    • parsers
    • search
    • security
    • tasks
    • testing
    • tools
    • validation
    • view
    • widgets
  • seo
    • open
      • graph
  • sfDateTimePlugin
  • spamprotection
  • stealth
    • captha
  • subsites
  • userform
    • pagetypes
  • userforms
  • webylon
  • widgets

Classes

  • Address
  • AddSubsiteTask
  • Announcement
  • AnnouncementDecorator
  • AnnouncementHolder
  • AssociatedFolderDecorator
  • AttachedFiles
  • AudioPhpCaptcha
  • AutoCompleteField
  • BaseMediawebImportParser
  • BookingOrder_StatusLog
  • CalendarUtil
  • CalendarWidgetExtention
  • CatalogCatalogLinkedDecorator
  • CatalogImportTask
  • CatalogOldFieldsDecorator
  • CatalogProductLinkedDecorator
  • CheckoutStep_ShippingMethod
  • ChequePayment
  • ClearHistoryTask
  • ClientEmailOrderNotification_SiteConfig
  • ClientVKOrderNotification_SiteConfig
  • CommentsSiteConfig
  • ContactsPage
  • CookieExtention
  • CostTableShippingRate
  • CustomMenu
  • CustomMenuAdmin
  • CustomMenuDecorator
  • CustomMenuHolder
  • CustomMenuItem
  • CustomPayment
  • DataObjectLoggerExtension
  • DataObjectSubsites
  • DefaultCMSActionDecorator
  • DeleteOldAssociatedFoldersTask
  • DocPage
  • DocumentDirection
  • DocumentHaving
  • DocumentSearchForm
  • DocumentSiteConfig
  • DocumentsPage
  • DocumentType
  • DOMUtil
  • ExtendPageAnnouncement
  • ExtendPageNews
  • ExtendPagePoll
  • FileOversizeDecorator
  • FindCyrillicSiteConfig
  • FolderRenameTask
  • GDMergeAlpha
  • HomePage
  • ImageAutoResize
  • ImageResizeTask
  • ImportAdmin
  • ImportAutoStartTask
  • ImportCatalogMessage
  • ImportConfig
  • ImportLog
  • ImportSiteConfig
  • ImportTask
  • LoggerAdmin
  • LogItem
  • ManagerEmailOrderNotification_SiteConfig
  • MapObject
  • MapObjectGroup
  • MapPage
  • MediawebForm
  • MediawebImportParser
  • MemberLoggerExtension
  • MultiUploadConfig
  • NearestEventExtention
  • NewDocumentsAdmin
  • News_Controller
  • NewsEntry
  • NewsEntry_Controller
  • NewsHolder
  • NewsHolder_Controller
  • NewsLiveCalendarWidget
  • NewsSiteConfig
  • Order_StatusLog
  • Orders1CExchange
  • PageHideFieldsExtension
  • PageInformerRates
  • PageInformerWeather
  • Payment_Failure
  • Payment_Processing
  • Payment_Result
  • Payment_Success
  • PaymentMethod
  • PaymentSiteConfig
  • PayPalPayment
  • PayPalPayment_Handler
  • PhoneField
  • PhotoAlbumExtentions
  • PhpCaptcha
  • PhpCaptchaColour
  • PhpCaptchaField
  • phpMorphy
  • phpMorphy_AncodesResolver_AsIs
  • phpMorphy_AncodesResolver_Proxy
  • phpMorphy_AncodesResolver_ToDialingAncodes
  • phpMorphy_AncodesResolver_ToText
  • phpMorphy_AnnotDecoder_Base
  • phpMorphy_AnnotDecoder_Common
  • phpMorphy_AnnotDecoder_Factory
  • phpMorphy_AnnotDecoder_Predict
  • phpMorphy_FilesBundle
  • phpMorphy_Fsa
  • phpMorphy_Fsa_Decorator
  • phpMorphy_Fsa_Proxy
  • phpMorphy_Fsa_Sparse_File
  • phpMorphy_Fsa_Sparse_Mem
  • phpMorphy_Fsa_Sparse_Shm
  • phpMorphy_Fsa_Tree_File
  • phpMorphy_Fsa_Tree_Mem
  • phpMorphy_Fsa_Tree_Shm
  • phpMorphy_Fsa_WordsCollector
  • phpMorphy_GramInfo
  • phpMorphy_GramInfo_AncodeCache
  • phpMorphy_GramInfo_Decorator
  • phpMorphy_Graminfo_File
  • phpMorphy_Graminfo_Mem
  • phpMorphy_GramInfo_Proxy
  • phpMorphy_GramInfo_Proxy_WithHeader
  • phpMorphy_GramInfo_RuntimeCaching
  • phpMorphy_Graminfo_Shm
  • phpMorphy_GrammemsProvider_Base
  • phpMorphy_GrammemsProvider_Decorator
  • phpMorphy_GrammemsProvider_Empty
  • phpMorphy_GrammemsProvider_Factory
  • phpMorphy_GrammemsProvider_ForFactory
  • phpMorphy_GrammemsProvider_ru_RU
  • phpMorphy_GramTab
  • phpMorphy_GramTab_Empty
  • phpMorphy_GramTab_Proxy
  • phpMorphy_Link
  • phpMorphy_Link_Annot
  • phpMorphy_Link_Base
  • phpMorphy_Morphier_Base
  • phpMorphy_Morphier_Bulk
  • phpMorphy_Morphier_Common
  • phpMorphy_Morphier_Empty
  • phpMorphy_Morphier_Finder_Base
  • phpMorphy_Morphier_Finder_Common
  • phpMorphy_Morphier_Finder_Predict_Databse
  • phpMorphy_Morphier_Finder_Predict_Suffix
  • phpMorphy_Morphier_Helper
  • phpMorphy_Morphier_Predict_Database
  • phpMorphy_Morphier_Predict_Suffix
  • phpMorphy_Morphier_PredictCollector
  • phpMorphy_Semaphore
  • phpMorphy_Semaphore_Empty
  • phpMorphy_Semaphore_Nix
  • phpMorphy_Semaphore_Win
  • phpMorphy_Shm_Cache
  • phpMorphy_Shm_Cache_FileDescriptor
  • phpMorphy_Shm_Header
  • phpMorphy_Source_Dba
  • phpMorphy_Source_Fsa
  • phpMorphy_State
  • phpMorphy_Storage
  • phpMorphy_Storage_Factory
  • phpMorphy_Storage_File
  • phpMorphy_Storage_Mem
  • phpMorphy_Storage_Proxy
  • phpMorphy_Storage_Shm
  • phpMorphy_UnicodeHelper
  • phpMorphy_UnicodeHelper_Base
  • phpMorphy_UnicodeHelper_MultiByteFixed
  • phpMorphy_UnicodeHelper_singlebyte
  • phpMorphy_UnicodeHelper_ucs_2be
  • phpMorphy_UnicodeHelper_ucs_2le
  • phpMorphy_UnicodeHelper_ucs_4be
  • phpMorphy_UnicodeHelper_ucs_4le
  • phpMorphy_UnicodeHelper_utf_16_Base
  • phpMorphy_UnicodeHelper_utf_16be
  • phpMorphy_UnicodeHelper_utf_16le
  • phpMorphy_UnicodeHelper_utf_32_Base
  • phpMorphy_UnicodeHelper_utf_32be
  • phpMorphy_UnicodeHelper_utf_32le
  • phpMorphy_UnicodeHelper_utf_8
  • phpMorphy_WordDescriptor
  • phpMorphy_WordDescriptor_Collection
  • phpMorphy_WordDescriptor_Collection_Serializer
  • phpMorphy_WordForm
  • ProductImportV1Decorator
  • ProductOldFieldsDecorator
  • ProductProductLinkedDecorator
  • PublHolder
  • Publication
  • PublicationSiteTree
  • RatingDataObject
  • RatingExtension
  • RealtySiteConfigDecorator
  • RecentComments
  • RecentFiles
  • RecentPages
  • RelatedPageLink
  • RepairImportTask
  • RoomRate_PriceField
  • RussianUpLower
  • SberbankPayment
  • SberbankPayment_Handler
  • SetMainSiteHomePageTypeTask
  • ShippingEstimator
  • ShippingPackage
  • ShowUserFromExtension
  • SiteConfigDecorator
  • SiteConfigSubsites
  • SiteTreeSubsites
  • SMSCOrderNotification_SiteConfig
  • SMSOrderNotification_SiteConfig
  • SortCMSActionDecorator
  • SS_Report_FakeQuery
  • SSMorphy
  • SSNController
  • SteppedCheckout_PageMessages
  • SubpageListField
  • SubscribeFormAllPagesExtension
  • SubsiteDropdownField
  • SubsiteReportWrapper
  • TableShippingRate
  • UnitellerPayment
  • UnitellerPayment_Handler
  • UnmoderatedComments
  • VideoManager
  • VideoSiteConfig
  • WatermarkImage
  • WatermarkSiteConfig
  • WebylonImportAdmin
  • WebylonImportCatalog
  • WeightTableShippingRate
  • XMLValidate
  • YaMoneyPayment
  • YaMoneyPayment_Handler
  • YMLExporter
  • YMLSiteConfig

Interfaces

  • ImportInterface
  • PaymentObjectInterface
  • phpMorphy_AncodesResolver_Interface
  • phpMorphy_AnnotDecoder_Interface
  • phpMorphy_Fsa_Interface
  • phpMorphy_GramInfo_Interace
  • phpMorphy_GrammemsProvider_Interface
  • phpMorphy_GramTab_Interface
  • phpMorphy_Morphier_Finder_Interface
  • phpMorphy_Morphier_Interface
  • phpMorphy_Shm_Cache_Interface
  • phpMorphy_Source_Interface

Exceptions

  • phpMorphy_Exception

Functions

  • column_sort
  • column_sort_callback_basic
  • encodeFileForEmail
  • encodeMultipart
  • getMimeType
  • htmlEmail
  • loadMimeTypes
  • phpmorphy_overload_mb_funcs
  • plaintextEmail
  • processHeaders
  • QuotedPrintable_encode
  • supressOutput
  • validateError
  • validEmailAddr
  • wrapImagesInline
  • wrapImagesInline_rewriter
  1 <?php
  2 /**
  3  * Свое поле для телефонов с валидацией
  4  * 
  5  * 
  6  */
  7 class PhoneField extends TextField {
  8     
  9     protected static $fixed_part = '';
 10     
 11     /**
 12      * Устаналивает фиксированную часть номера для всех полей PhoneField на сайте
 13      * 
 14      * @param string $part 
 15      */
 16     static function set_fixed_part($part) {
 17         self::$fixed_part = $part;
 18     }
 19     
 20     protected static $max_length = 15; // по стандарту E164
 21 
 22     /**
 23      * Устаналивает максимальную длину номера для всех полей PhoneField на сайте
 24      * 
 25      * @param int $val 
 26      */
 27     static function set_max_length($val) {
 28         self::$max_length = $val;
 29     }
 30 
 31     protected static $min_length = 3; // если только локальный
 32 
 33     /**
 34      * Устаналивает минимальную длину номера для всех полей PhoneField на сайте
 35      * 
 36      * @param int $val 
 37      */
 38     static function set_min_length($val) {
 39         self::$min_length = $val;
 40     }
 41     
 42     // пока не используем, т.к. все проверяется регуляркой и не дает ввести неправильное
 43     static $value_searches = array(
 44         '/[^\d+]+/', // не цифры и "+" - в топку
 45         //'/^8([^8]\d{9})/', // полный Российский номер на 8 меняем на 7 (кроме 8-800-*)
 46     );
 47 
 48     static $value_replaces = array(
 49         '',
 50         //'7$1',
 51     );
 52     
 53     /**
 54      * Добавляет замену в список замен
 55      * 
 56      * @param string $from 
 57      * @param string $to 
 58      */
 59     static function add_replace($from, $to) {
 60         self::$value_searches[] = $from;
 61         self::$value_replaces[] = $to;
 62     }
 63     
 64     /**
 65      * Заменяет список замен
 66      * 
 67      * @param array $from 
 68      * @param array $to 
 69      */
 70     static function set_replaces($from, $to) {
 71         self::$value_searches = $from;
 72         self::$value_replaces = $to;
 73     }
 74 
 75     
 76     /**
 77      * Выполняет преобразования телефонного номера
 78      * 
 79      * @param string $val - "грязный" номер
 80      * 
 81      * @return string - "чистый" номер
 82      */
 83     static function cleanup_phone($val) {
 84         $val = trim($val);
 85         if (count(self::$value_searches) > 0 && count(self::$value_searches) == count(self::$value_replaces)) {
 86             return preg_replace(self::$value_searches, self::$value_replaces, $val); // в принцие, 8 в начале не пройдет валидацию, но возможно пригодится для чего-то еще
 87         }
 88         return $val;
 89     }
 90     
 91     // фиксированная часть конкретного поля
 92     protected $fixedPart = false;
 93     
 94     // минимальная длина конкретного поля
 95     protected $minLength = false;
 96     
 97     function setFixedPart($value) {
 98         $this->fixedPart = $value;
 99         if (!$this->value || ($this->value == self::$fixed_part))
100             $this->setValue($value);
101     }
102     
103     /**
104      * Возвращает фиксированную часть номера 
105      * 
106      * @return string
107      */
108     function getFixedPart() {
109         if ($this->fixedPart !== false) {
110             return $this->fixedPart;
111         }
112         return self::$fixed_part;
113     }
114     
115     function setMinLength($val) {
116         $this->minLength = $val;
117     }
118     
119     function getMinLength() {
120         if ($this->minLength !== false) {
121             return $this->minLength;
122         }
123         return self::$min_length;
124     }
125     
126     function __construct($name, $title = null, $value = "", $maxLength = null, $form = null){
127         if (!$value) {
128             $value = $this->getFixedPart();
129         }
130         if (!$maxLength) {
131             $maxLength = self::$max_length;
132         }
133         
134         $this->setHTML5Attribute('type', 'tel');
135         $this->setAutocomplete('tel');
136 
137         parent::__construct($name, $title, $value, $maxLength, $form);
138     }
139 
140     function Field() {
141         $pattern = $this->getValidationRegexp();
142         // выкидываем лидирующий и финишный / для атрибута pattern
143         $pattern = preg_replace("/^\//", "", $pattern);
144         $pattern = preg_replace("/\/$/", "", $pattern);
145         $this->setHTML5Attribute('pattern', $pattern);
146         return parent::Field();
147     }
148     
149     /**
150      * Формирует regexp для валидации номера
151      * 
152      * @return string
153      */
154     function getValidationRegexp() {
155         $max = $this->getMaxLength() - strlen($this->getFixedPart());
156         $min = max($this->getMinLength() - strlen($this->getFixedPart()), 0);
157         $min = min($min, $max);
158         return sprintf("/^\+?%s\d{%d,%d}$/", preg_quote(str_replace('+','', $this->getFixedPart())), $min, $max);
159     }
160     
161     function jsValidation() {
162         $formID = $this->form->FormName();
163         $error = _t('PhoneField.VALIDATIONJS', 'Please enter correct phone.');
164         $regexp = $this->getValidationRegexp();
165         
166         $jsFunc =<<<JS
167 Behaviour.register({
168     "#$formID": {
169         validatePhoneField: function(fieldName) {
170             var el = _CURRENT_FORM.elements[fieldName];
171             if(!el || !el.value) return true;
172             var val = el.value.replace(/[^0-9+]+/g, '');
173             if(val.match({$regexp})) {
174                 return true;
175             } else {
176                 validationError(el, "$error","validation");
177                 return false;
178             }   
179         }
180     }
181 });
182 JS;
183         //fix for the problem with more than one form on a page.
184         Requirements::customScript($jsFunc, 'func_validatePhoneField' .'_' . $formID);
185 
186         return <<<JS
187 if(typeof fromAnOnBlur != 'undefined'){
188     if(fromAnOnBlur.name == '$this-me')
189         $('$formID').validatePhoneField('$this-me');
190 }else{
191     $('$formID').validatePhoneField('$this->name');
192 }
193 JS;
194     }
195     
196     function validate($validator){
197         $this->value = self::cleanup_phone($this->value);
198         if ($this->value && !preg_match($this->getValidationRegexp(), $this->value)){
199             if ($validator) {
200                 $validator->validationError(
201                     $this->name,
202                     _t('PhoneField.VALIDATION', "Please enter correct phone."),
203                     "validation"
204                 );
205             }
206             return false;
207         } 
208         else {
209             return parent::validate($validator);
210         }
211     }
212     
213     /**
214      * Подготоваливает данные к записи в БД
215      * Производит необходимые замены в номере
216      * 
217      * @return string
218      */
219     function dataValue() {
220         return self::cleanup_phone($this->value);
221     }
222 }
223 
[Raise a SilverStripe Framework issue/bug](https://github.com/silverstripe/silverstripe-framework/issues/new)
- [Raise a SilverStripe CMS issue/bug](https://github.com/silverstripe/silverstripe-cms/issues/new)
- Please use the Silverstripe Forums to ask development related questions. -
Webylon 3.1 API Docs API documentation generated by ApiGen 2.8.0