Phundament App Class Reference
  • Package
  • Class
  • Tree

Packages

  • bootstrap
    • widgets
      • input
  • Image
  • None
  • p3admin
  • p3extensions
    • behaviors
    • commands
    • components
    • helpers
    • widgets
  • p3media
    • actions
    • controllers
    • models
  • p3pages
    • models
  • p3widgets
    • components
    • models
  • PHP
  • system
    • db
      • ar
    • gii
    • web
      • auth
      • helpers
      • widgets
  • yiiext
    • widgets
      • fancybox
      • lipsum
  • zii
    • widgets
      • grid

Classes

  • ActivationController
  • AdminController
  • AssignmentController
  • AssignmentForm
  • AuthChildForm
  • AuthItemController
  • AuthItemForm
  • BaseP3Widget
  • BaseP3WidgetMeta
  • BaseP3WidgetTranslation
  • Bootstrap
  • CImageComponent
  • CKEditor
  • CodeProvider
  • DefaultController
  • EChosen
  • EDbMigration
  • EditableField
  • EditableSaver
  • EMigrateCommand
  • ESelect2
  • EUserFlash
  • FullCrudFieldProvider
  • GenerateForm
  • IdentificationColumnValidator
  • InstallController
  • JSONEditorView
  • JuiJSONEditorInput
  • LoginController
  • LogoutController
  • Metadata
  • P3CrudFieldProvider
  • P3MediaController
  • P3MediaMetaController
  • P3MediaSelect
  • P3PageController
  • P3PageMetaController
  • P3PageTranslationController
  • P3Widget
  • P3WidgetController
  • P3WidgetMetaController
  • P3WidgetTranslation
  • P3WidgetTranslationController
  • ProfileController
  • ProfileFieldController
  • RAuthItemBehavior
  • RAuthItemChildDataProvider
  • RAuthItemDataProvider
  • RAuthItemParentDataProvider
  • RAuthorizer
  • RController
  • RDbAuthManager
  • RecoveryController
  • RegistrationController
  • RegistrationForm
  • RGenerator
  • Rights
  • RightsFilter
  • RightsModule
  • RInstaller
  • RPermissionDataProvider
  • RUserBehavior
  • RWebUser
  • UActiveForm
  • UploadHandler
  • UserChangePassword
  • UserController
  • UserIdentity
  • UserLogin
  • UserModule
  • UserRecoveryForm
  • UWdropDownDep
  • UWfile
  • UWjuiAutoComplete
  • UWjuidate
  • UWrelBelongsTo
  • WebUserBehavior
  1 <?php
  2 /**
  3  * EditableField class file.
  4  * 
  5  * This widget makes editable single attribute of model
  6  * 
  7  * @author Vitaliy Potapov <noginsk@rambler.ru>
  8  * @link https://github.com/vitalets/yii-bootstrap-editable
  9  * @copyright Copyright &copy; Vitaliy Potapov 2012
 10  * @license http://www.opensource.org/licenses/bsd-license.php New BSD License
 11  * @version 1.0.0
 12  */
 13  
 14 class EditableField extends CWidget
 15 {
 16     //for all types
 17     public $model = null;
 18     public $attribute = null;
 19     public $type = null;
 20     public $url = null;
 21     public $title = null;
 22     public $emptytext = null;
 23     public $text = null; //will be used as content
 24     public $value = null;
 25     public $placement = null;
 26     public $inputclass = null;
 27     public $autotext = null;
 28 
 29     //for text & textarea
 30     public $placeholder = null;
 31     
 32     //for select
 33     public $source = array();
 34     public $prepend = null;
 35 
 36     //for date
 37     public $format = null;
 38     public $viewformat = null;
 39     public $language = null;
 40     public $weekStart = null;
 41     public $startView = null;
 42 
 43     //methods
 44     public $validate = null;
 45     public $success = null;
 46     public $error = null;
 47     
 48     //events
 49     public $onInit = null;
 50     public $onUpdate = null;
 51     public $onRender = null;
 52     public $onShown = null;
 53     public $onHidden = null;
 54 
 55     //js options
 56     public $options = array();
 57     
 58     //html options
 59     public $htmlOptions = array();
 60 
 61     //weather to encode text on output
 62     public $encode = true;
 63 
 64     //if false text will not be editable, but will be rendered
 65     public $enabled = null;
 66 
 67     public function init()
 68     {   
 69         if (!$this->model) {
 70             throw new CException('Parameter "model" should be provided for Editable');
 71         }
 72         if (!$this->attribute) {
 73             throw new CException('Parameter "attribute" should be provided for Editable');
 74         }
 75         if (!$this->model->hasAttribute($this->attribute)) {
 76             throw new CException('Model "'.get_class($this->model).'" does not have attribute "'.$this->attribute.'"');
 77         }        
 78  
 79         parent::init();
 80                 
 81         if ($this->type === null) {
 82             $this->type = 'text';
 83             //try detect type from metadata.
 84             if (array_key_exists($this->attribute, $this->model->tableSchema->columns)) {
 85                 $dbType = $this->model->tableSchema->columns[$this->attribute]->dbType;
 86                 if($dbType == 'date' || $dbType == 'datetime') $this->type = 'date';
 87                 if(stripos($dbType, 'text') !== false) $this->type = 'textarea';
 88             }
 89         }
 90 
 91         /*
 92         * unfortunatly datepicker's format does not match Yii locale dateFormat
 93         * and we cannot take format from application locale
 94         * 
 95         * see http://www.unicode.org/reports/tr35/#Date_Format_Patterns
 96         * 
 97         if($this->type == 'date' && $this->format === null) {
 98             $this->format = Yii::app()->locale->getDateFormat();
 99         }
100         */
101         
102         /* generate text from model attribute (for all types except 'select'. 
103         *  For select/date autotext will be applied)
104         */ 
105         if (!strlen($this->text) && $this->type != 'select' && $this->type != 'date') {
106             $this->text = $this->model->getAttribute($this->attribute);
107         }
108 
109         //if enabled not defined directly, set it to true only for safe attributes
110         if($this->enabled === null) {
111             $this->enabled = $this->model->isAttributeSafe($this->attribute);
112         }
113         
114         //if not enabled --> just print text        
115         if (!$this->enabled) {
116             return;
117         }
118 
119         //language: use config's value if not defined directly
120         if ($this->language === null && yii::app()->language) {
121             $this->language = yii::app()->language;
122         }
123 
124         //normalize url from array if needed
125         $this->url = CHtml::normalizeUrl($this->url);
126 
127         //generate title from attribute label
128         if ($this->title === null) {
129             //todo: i18n here. Add messages folder to extension
130             $this->title = (($this->type == 'select' || $this->type == 'date') ? Yii::t('editable', 'Select') : Yii::t('editable', 'Enter')) . ' ' . $this->model->getAttributeLabel($this->attribute);
131         }
132 
133         $this->buildHtmlOptions();
134         $this->buildJsOptions();
135         $this->registerAssets();
136     }
137 
138     public function buildHtmlOptions()
139     {
140         //html options
141         $htmlOptions = array(
142             'href'      => '#',
143             'rel'       => $this->getSelector(),
144             'data-pk'   => $this->model->primaryKey,
145         );
146 
147         //for select we need to define value directly
148         if ($this->type == 'select') {
149             $this->value = $this->model->getAttribute($this->attribute);
150             $this->htmlOptions['data-value'] = $this->value;
151         }
152         
153         //for date we use 'format' to put it into value (if text not defined)
154         if ($this->type == 'date' && !strlen($this->text)) {
155             $this->value = $this->model->getAttribute($this->attribute);
156             
157             //if date comes as object, format it to string
158             if($this->value instanceOf DateTime) {
159                 /* 
160                 * unfortunatly datepicker's format does not match Yii locale dateFormat,
161                 * we need replacements below to convert date correctly
162                 */
163                 $count = 0;
164                 $format = str_replace('MM', 'MMMM', $this->format, $count);
165                 if(!$count) $format = str_replace('M', 'MMM', $format, $count);
166                 if(!$count) $format = str_replace('m', 'M', $format);
167                 
168                 $this->value = Yii::app()->dateFormatter->format($format, $this->value->getTimestamp()); 
169             }            
170             
171             $this->htmlOptions['data-value'] = $this->value;
172         }        
173 
174         //merging options
175         $this->htmlOptions = CMap::mergeArray($this->htmlOptions, $htmlOptions);
176     }
177 
178     public function buildJsOptions()
179     {
180         $options = array(
181             'type'  => $this->type,
182             'url'   => $this->url,
183             'name'  => $this->attribute,
184             'title' => CHtml::encode($this->title),
185         );
186 
187         if ($this->emptytext) {
188             $options['emptytext'] = $this->emptytext;
189         }
190         
191         if ($this->placement) {
192             $options['placement'] = $this->placement;
193         }
194         
195         if ($this->inputclass) {
196             $options['inputclass'] = $this->inputclass;
197         }    
198         
199         if ($this->autotext) {
200             $options['autotext'] = $this->autotext;
201         }            
202 
203         switch ($this->type) {
204             case 'text':
205             case 'textarea':
206                 if ($this->placeholder) {
207                     $options['placeholder'] = $this->placeholder;
208                 }
209                 break;
210             case 'select':
211                 if ($this->source) {
212                     $options['source'] = $this->source;
213                 }
214                 if ($this->prepend) {
215                     $options['prepend'] = $this->prepend;
216                 }
217                 break;
218             case 'date':
219                 if ($this->format) {
220                     $options['format'] = $this->format;
221                 }
222                 if ($this->viewformat) {
223                     $options['viewformat'] = $this->viewformat;
224                 }                
225                 if ($this->language && substr($this->language, 0, 2) != 'en') {
226                     $options['datepicker']['language'] = $this->language;
227                 }
228                 if ($this->weekStart !== null) {
229                     $options['weekStart'] = $this->weekStart;
230                 }
231                 if ($this->startView !== null) {
232                     $options['startView'] = $this->startView;
233                 }
234                 break;
235         }
236 
237         //methods
238         foreach(array('validate', 'success', 'error') as $event) {
239             if($this->$event!==null) {
240                 $options[$event]=(strpos($this->$event, 'js:') !== 0 ? 'js:' : '') . $this->$event;
241             }
242         }        
243 
244         //merging options
245         $this->options = CMap::mergeArray($this->options, $options);
246     }
247 
248     public function registerClientScript()
249     {
250         $script = "$('a[rel={$this->htmlOptions['rel']}]')";
251           
252         //attach events
253         foreach(array('init', 'update', 'render', 'shown', 'hidden') as $event) {
254             $property = 'on'.ucfirst($event); 
255             if ($this->$property) {
256                 // CJavaScriptExpression appeared only in 1.1.11, will turn to it later
257                 //$event = ($this->onInit instanceof CJavaScriptExpression) ? $this->onInit : new CJavaScriptExpression($this->onInit);
258                 $eventJs = (strpos($this->$property, 'js:') !== 0 ? 'js:' : '') . $this->$property;
259                 $script .= "\n.on('".$event."', ".CJavaScript::encode($eventJs).")";
260             }
261         }
262 
263         //apply editable
264         $options = CJavaScript::encode($this->options);        
265         $script .= ".editable($options);";
266         
267         Yii::app()->getClientScript()->registerScript(__CLASS__ . '#' . $this->id, $script);
268         
269         return $script;
270     }
271 
272 
273     public function registerAssets()
274     {
275         //if bootstrap extension installed, but no js registered -> register it!
276         if (($bootstrap = yii::app()->getComponent('bootstrap')) && !$bootstrap->enableJS) {
277             $bootstrap->registerCorePlugins(); //enable bootstrap js if needed
278         }
279 
280         $assetsUrl = Yii::app()->getAssetManager()->publish(Yii::getPathOfAlias('ext.editable.assets'), false, 1); //publish excluding datepicker locales
281         Yii::app()->getClientScript()->registerCssFile($assetsUrl . '/css/bootstrap-editable.css');
282         Yii::app()->clientScript->registerScriptFile($assetsUrl . '/js/bootstrap-editable.js', CClientScript::POS_END);
283 
284         //include locale for datepicker
285         if ($this->type == 'date' && $this->language && substr($this->language, 0, 2) != 'en') {
286              //todo: check compare dp locale name with yii's
287              $localesUrl = Yii::app()->getAssetManager()->publish(Yii::getPathOfAlias('ext.editable.assets.js.locales'));
288              Yii::app()->clientScript->registerScriptFile($localesUrl . '/bootstrap-datepicker.'. str_replace('_', '-', $this->language).'.js', CClientScript::POS_END);
289         }
290     }
291 
292     public function run()
293     {
294         if($this->enabled) {
295             $this->registerClientScript();
296             $this->renderLink();
297         } else {
298             $this->renderText();
299         }
300     }
301 
302     public function renderLink()
303     {
304         echo CHtml::openTag('a', $this->htmlOptions);
305         $this->renderText();
306         echo CHtml::closeTag('a');
307     }
308 
309     public function renderText()
310     {   
311         $encodedText = $this->encode ? CHtml::encode($this->text) : $this->text;
312         if($this->type == 'textarea') {
313              $encodedText = preg_replace('/\r?\n/', '<br>', $encodedText);
314         }
315         echo $encodedText;
316     }    
317     
318     public function getSelector()
319     {
320         return get_class($this->model) . '_' . $this->attribute . ($this->model->primaryKey ? '_' . $this->model->primaryKey : '_new');
321     }
322 }
323 
Phundament App Class Reference API documentation generated by ApiGen 2.8.0