PageRenderTime 48ms CodeModel.GetById 15ms RepoModel.GetById 0ms app.codeStats 0ms

/yii/framework/web/widgets/CActiveForm.php

https://github.com/joshuaswarren/weatherhub
PHP | 752 lines | 212 code | 36 blank | 504 comment | 37 complexity | bf00bf1757fdc096701afa24b45f1a74 MD5 | raw file
  1. <?php
  2. /**
  3. * CActiveForm class file.
  4. *
  5. * @author Qiang Xue <qiang.xue@gmail.com>
  6. * @link http://www.yiiframework.com/
  7. * @copyright Copyright &copy; 2008-2011 Yii Software LLC
  8. * @license http://www.yiiframework.com/license/
  9. */
  10. /**
  11. * CActiveForm provides a set of methods that can help to simplify the creation
  12. * of complex and interactive HTML forms that are associated with data models.
  13. *
  14. * The 'beginWidget' and 'endWidget' call of CActiveForm widget will render
  15. * the open and close form tags. Most other methods of CActiveForm are wrappers
  16. * of the corresponding 'active' methods in {@link CHtml}. Calling them in between
  17. * the 'beginWidget' and 'endWidget' calls will render text labels, input fields,
  18. * etc. For example, calling {@link CActiveForm::textField}
  19. * would generate an input field for a specified model attribute.
  20. *
  21. * What makes CActiveForm extremely useful is its support for data validation.
  22. * CActiveForm supports data validation at three levels:
  23. * <ul>
  24. * <li>server-side validation: the validation is performed at server side after
  25. * the whole page containing the form is submitted. If there is any validation error,
  26. * CActiveForm will render the error in the page back to user.</li>
  27. * <li>AJAX-based validation: when the user enters data into an input field,
  28. * an AJAX request is triggered which requires server-side validation. The validation
  29. * result is sent back in AJAX response and the input field changes its appearance
  30. * accordingly.</li>
  31. * <li>client-side validation (available since version 1.1.7):
  32. * when the user enters data into an input field,
  33. * validation is performed on the client side using JavaScript. No server contact
  34. * will be made, which reduces the workload on the server.</li>
  35. * </ul>
  36. *
  37. * All these validations share the same set of validation rules declared in
  38. * the associated model class. CActiveForm is designed in such a way that
  39. * all these validations will lead to the same user interface changes and error
  40. * message content.
  41. *
  42. * To ensure data validity, server-side validation is always performed.
  43. * By setting {@link enableAjaxValidation} to true, one can enable AJAX-based validation;
  44. * and by setting {@link enableClientValidation} to true, one can enable client-side validation.
  45. * Note that in order to make the latter two validations work, the user's browser
  46. * must has its JavaScript enabled. If not, only the server-side validation will
  47. * be performed.
  48. *
  49. * The AJAX-based validation and client-side validation may be used together
  50. * or separately. For example, in a user registration form, one may use AJAX-based
  51. * validation to check if the user has picked a unique username, and use client-side
  52. * validation to ensure all required fields are entered with data.
  53. * Because the AJAX-based validation may bring extra workload on the server,
  54. * if possible, one should mainly use client-side validation.
  55. *
  56. * The AJAX-based validation has a few limitations. First, it does not work
  57. * with file upload fields. Second, it should not be used to perform validations that
  58. * may cause server-side state changes. Third, it is not designed
  59. * to work with tabular data input for the moment.
  60. *
  61. * Support for client-side validation varies for different validators. A validator
  62. * will support client-side validation only if it implements {@link CValidator::clientValidateAttribute}
  63. * and has its {@link CValidator::enableClientValidation} property set true.
  64. * At this moment, the following core validators support client-side validation:
  65. * <ul>
  66. * <li>{@link CBooleanValidator}</li>
  67. * <li>{@link CCaptchaValidator}</li>
  68. * <li>{@link CCompareValidator}</li>
  69. * <li>{@link CEmailValidator}</li>
  70. * <li>{@link CNumberValidator}</li>
  71. * <li>{@link CRangeValidator}</li>
  72. * <li>{@link CRegularExpressionValidator}</li>
  73. * <li>{@link CRequiredValidator}</li>
  74. * <li>{@link CStringValidator}</li>
  75. * <li>{@link CUrlValidator}</li>
  76. * </ul>
  77. *
  78. * CActiveForm relies on CSS to customize the appearance of input fields
  79. * which are in different validation states. In particular, each input field
  80. * may be one of the four states: initial (not validated),
  81. * validating, error and success. To differentiate these states, CActiveForm
  82. * automatically assigns different CSS classes for the last three states
  83. * to the HTML element containing the input field.
  84. * By default, these CSS classes are named as 'validating', 'error' and 'success',
  85. * respectively. We may customize these CSS classes by configuring the
  86. * {@link clientOptions} property or specifying in the {@link error} method.
  87. *
  88. * The following is a piece of sample view code showing how to use CActiveForm:
  89. *
  90. * <pre>
  91. * <?php $form = $this->beginWidget('CActiveForm', array(
  92. * 'id'=>'user-form',
  93. * 'enableAjaxValidation'=>true,
  94. * 'enableClientValidation'=>true,
  95. * 'focus'=>array($model,'firstName'),
  96. * )); ?>
  97. *
  98. * <?php echo $form->errorSummary($model); ?>
  99. *
  100. * <div class="row">
  101. * <?php echo $form->labelEx($model,'firstName'); ?>
  102. * <?php echo $form->textField($model,'firstName'); ?>
  103. * <?php echo $form->error($model,'firstName'); ?>
  104. * </div>
  105. * <div class="row">
  106. * <?php echo $form->labelEx($model,'lastName'); ?>
  107. * <?php echo $form->textField($model,'lastName'); ?>
  108. * <?php echo $form->error($model,'lastName'); ?>
  109. * </div>
  110. *
  111. * <?php $this->endWidget(); ?>
  112. * </pre>
  113. *
  114. * To respond to the AJAX validation requests, we need the following class code:
  115. * <pre>
  116. * public function actionCreate()
  117. * {
  118. * $model=new User;
  119. * $this->performAjaxValidation($model);
  120. * if(isset($_POST['User']))
  121. * {
  122. * $model->attributes=$_POST['User'];
  123. * if($model->save())
  124. * $this->redirect('index');
  125. * }
  126. * $this->render('create',array('model'=>$model));
  127. * }
  128. *
  129. * protected function performAjaxValidation($model)
  130. * {
  131. * if(isset($_POST['ajax']) && $_POST['ajax']==='user-form')
  132. * {
  133. * echo CActiveForm::validate($model);
  134. * Yii::app()->end();
  135. * }
  136. * }
  137. * </pre>
  138. *
  139. * In the above code, if we do not enable the AJAX-based validation, we can remove
  140. * the <code>performAjaxValidation</code> method and its invocation.
  141. *
  142. * @author Qiang Xue <qiang.xue@gmail.com>
  143. * @version $Id: CActiveForm.php 3253 2011-06-10 23:19:08Z keyboard.idol@gmail.com $
  144. * @package system.web.widgets
  145. * @since 1.1.1
  146. */
  147. class CActiveForm extends CWidget
  148. {
  149. /**
  150. * @var mixed the form action URL (see {@link CHtml::normalizeUrl} for details about this parameter).
  151. * If not set, the current page URL is used.
  152. */
  153. public $action='';
  154. /**
  155. * @var string the form submission method. This should be either 'post' or 'get'.
  156. * Defaults to 'post'.
  157. */
  158. public $method='post';
  159. /**
  160. * @var boolean whether to generate a stateful form (See {@link CHtml::statefulForm}). Defaults to false.
  161. */
  162. public $stateful=false;
  163. /**
  164. * @var string the CSS class name for error messages. Defaults to 'errorMessage'.
  165. * Individual {@link error} call may override this value by specifying the 'class' HTML option.
  166. */
  167. public $errorMessageCssClass='errorMessage';
  168. /**
  169. * @var array additional HTML attributes that should be rendered for the form tag.
  170. */
  171. public $htmlOptions=array();
  172. /**
  173. * @var array the options to be passed to the javascript validation plugin.
  174. * The following options are supported:
  175. * <ul>
  176. * <li>ajaxVar: string, the name of the parameter indicating the request is an AJAX request.
  177. * When the AJAX validation is triggered, a parameter named as this property will be sent
  178. * together with the other form data to the server. The parameter value is the form ID.
  179. * The server side can then detect who triggers the AJAX validation and react accordingly.
  180. * Defaults to 'ajax'.</li>
  181. * <li>validationUrl: string, the URL that performs the AJAX validations.
  182. * If not set, it will take the value of {@link action}.</li>
  183. * <li>validationDelay: integer, the number of milliseconds that an AJAX validation should be
  184. * delayed after an input is changed. A value 0 means the validation will be triggered immediately
  185. * when an input is changed. A value greater than 0 means changing several inputs may only
  186. * trigger a single validation if they happen fast enough, which may help reduce the server load.
  187. * Defaults to 200 (0.2 second).</li>
  188. * <li>validateOnSubmit: boolean, whether to perform AJAX validation when the form is being submitted.
  189. * If there are any validation errors, the form submission will be stopped.
  190. * Defaults to false.</li>
  191. * <li>validateOnChange: boolean, whether to trigger an AJAX validation
  192. * each time when an input's value is changed. You may want to turn this off
  193. * if it causes too much performance impact, because each AJAX validation request
  194. * will submit the data of the whole form. Defaults to true.</li>
  195. * <li>validateOnType: boolean, whether to trigger an AJAX validation each time when the user
  196. * presses a key. When setting this property to be true, you should tune up the 'validationDelay'
  197. * option to avoid triggering too many AJAX validations. Defaults to false.</li>
  198. * <li>hideErrorMessage: boolean, whether to hide the error message even if there is an error.
  199. * Defaults to false, which means the error message will show up whenever the input has an error.</li>
  200. * <li>inputContainer: string, the jQuery selector for the HTML element containing the input field.
  201. * During the validation process, CActiveForm will set different CSS class for the container element
  202. * to indicate the state change. If not set, it means the closest 'div' element that contains the input field.</li>
  203. * <li>errorCssClass: string, the CSS class to be assigned to the container whose associated input
  204. * has AJAX validation error. Defaults to 'error'.</li>
  205. * <li>successCssClass: string, the CSS class to be assigned to the container whose associated input
  206. * passes AJAX validation without any error. Defaults to 'success'.</li>
  207. * <li>validatingCssClass: string, the CSS class to be assigned to the container whose associated input
  208. * is currently being validated via AJAX. Defaults to 'validating'.</li>
  209. * <li>errorMessageCssClass: string, the CSS class assigned to the error messages returned
  210. * by AJAX validations. Defaults to 'errorMessage'.</li>
  211. * <li>beforeValidate: function, the function that will be invoked before performing ajax-based validation
  212. * triggered by form submission action (available only when validateOnSubmit is set true).
  213. * The expected function signature should be <code>beforeValidate(form) {...}</code>, where 'form' is
  214. * the jquery representation of the form object. If the return value of this function is NOT true, the validation
  215. * will be cancelled.
  216. *
  217. * Note that because this option refers to a js function, you should prefix the value with 'js:' to prevent it
  218. * from being encoded as a string. This option has been available since version 1.1.3.</li>
  219. * <li>afterValidate: function, the function that will be invoked after performing ajax-based validation
  220. * triggered by form submission action (available only when validateOnSubmit is set true).
  221. * The expected function signature should be <code>afterValidate(form, data, hasError) {...}</code>, where 'form' is
  222. * the jquery representation of the form object; 'data' is the JSON response from the server-side validation; 'hasError'
  223. * is a boolean value indicating whether there is any validation error. If the return value of this function is NOT true,
  224. * the normal form submission will be cancelled.
  225. *
  226. * Note that because this option refers to a js function, you should prefix the value with 'js:' to prevent it
  227. * from being encoded as a string. This option has been available since version 1.1.3.</li>
  228. * <li>beforeValidateAttribute: function, the function that will be invoked before performing ajax-based validation
  229. * triggered by a single attribute input change. The expected function signature should be
  230. * <code>beforeValidateAttribute(form, attribute) {...}</code>, where 'form' is the jquery representation of the form object
  231. * and 'attribute' refers to the js options for the triggering attribute (see {@link error}).
  232. * If the return value of this function is NOT true, the validation will be cancelled.
  233. *
  234. * Note that because this option refers to a js function, you should prefix the value with 'js:' to prevent it
  235. * from being encoded as a string. This option has been available since version 1.1.3.</li>
  236. * <li>afterValidateAttribute: function, the function that will be invoked after performing ajax-based validation
  237. * triggered by a single attribute input change. The expected function signature should be
  238. * <code>beforeValidateAttribute(form, attribute, data, hasError) {...}</code>, where 'form' is the jquery
  239. * representation of the form object; 'attribute' refers to the js options for the triggering attribute (see {@link error});
  240. * 'data' is the JSON response from the server-side validation; 'hasError' is a boolean value indicating whether
  241. * there is any validation error.
  242. *
  243. * Note that because this option refers to a js function, you should prefix the value with 'js:' to prevent it
  244. * from being encoded as a string. This option has been available since version 1.1.3.</li>
  245. * </ul>
  246. *
  247. * Some of the above options may be overridden in individual calls of {@link error()}.
  248. * They include: validationDelay, validateOnChange, validateOnType, hideErrorMessage,
  249. * inputContainer, errorCssClass, successCssClass, validatingCssClass, beforeValidateAttribute, afterValidateAttribute.
  250. */
  251. public $clientOptions=array();
  252. /**
  253. * @var boolean whether to enable data validation via AJAX. Defaults to false.
  254. * When this property is set true, you should respond to the AJAX validation request on the server side as shown below:
  255. * <pre>
  256. * public function actionCreate()
  257. * {
  258. * $model=new User;
  259. * if(isset($_POST['ajax']) && $_POST['ajax']==='user-form')
  260. * {
  261. * echo CActiveForm::validate($model);
  262. * Yii::app()->end();
  263. * }
  264. * ......
  265. * }
  266. * </pre>
  267. */
  268. public $enableAjaxValidation=false;
  269. /**
  270. * @var boolean whether to enable client-side data validation. Defaults to false.
  271. *
  272. * When this property is set true, client-side validation will be performed by validators
  273. * that support it (see {@link CValidator::enableClientValidation} and {@link CValidator::clientValidateAttribute}).
  274. *
  275. * @see error
  276. * @since 1.1.7
  277. */
  278. public $enableClientValidation=false;
  279. /**
  280. * @var mixed form element to get initial input focus on page load.
  281. *
  282. * Defaults to null meaning no input field has a focus.
  283. * If set as array, first element should be model and second element should be the attribute.
  284. * If set as string any jQuery selector can be used
  285. *
  286. * Example - set input focus on page load to:
  287. * <ul>
  288. * <li>'focus'=>array($model,'username') - $model->username input filed</li>
  289. * <li>'focus'=>'#'.CHtml::activeId($model,'username') - $model->username input field</li>
  290. * <li>'focus'=>'#LoginForm_username' - input field with ID LoginForm_username</li>
  291. * <li>'focus'=>'input[type="text"]:first' - first input element of type text</li>
  292. * <li>'focus'=>'input:visible:enabled:first' - first visible and enabled input element</li>
  293. * <li>'focus'=>'input:text[value=""]:first' - first empty input</li>
  294. * </ul>
  295. *
  296. * @since 1.1.4
  297. */
  298. public $focus;
  299. /**
  300. * @var array the javascript options for model attributes (input ID => options)
  301. * @see error
  302. * @since 1.1.7
  303. */
  304. protected $attributes=array();
  305. /**
  306. * @var string the ID of the container element for error summary
  307. * @see errorSummary
  308. * @since 1.1.7
  309. */
  310. protected $summaryID;
  311. /**
  312. * Initializes the widget.
  313. * This renders the form open tag.
  314. */
  315. public function init()
  316. {
  317. if(!isset($this->htmlOptions['id']))
  318. $this->htmlOptions['id']=$this->id;
  319. if($this->stateful)
  320. echo CHtml::statefulForm($this->action, $this->method, $this->htmlOptions);
  321. else
  322. echo CHtml::beginForm($this->action, $this->method, $this->htmlOptions);
  323. }
  324. /**
  325. * Runs the widget.
  326. * This registers the necessary javascript code and renders the form close tag.
  327. */
  328. public function run()
  329. {
  330. if(is_array($this->focus))
  331. $this->focus="#".CHtml::activeId($this->focus[0],$this->focus[1]);
  332. echo CHtml::endForm();
  333. $cs=Yii::app()->clientScript;
  334. if(!$this->enableAjaxValidation && !$this->enableClientValidation || empty($this->attributes))
  335. {
  336. if($this->focus!==null)
  337. {
  338. $cs->registerCoreScript('jquery');
  339. $cs->registerScript('CActiveForm#focus',"
  340. if(!window.location.hash)
  341. $('".$this->focus."').focus();
  342. ");
  343. }
  344. return;
  345. }
  346. $options=$this->clientOptions;
  347. if(isset($this->clientOptions['validationUrl']) && is_array($this->clientOptions['validationUrl']))
  348. $options['validationUrl']=CHtml::normalizeUrl($this->clientOptions['validationUrl']);
  349. $options['attributes']=array_values($this->attributes);
  350. if($this->summaryID!==null)
  351. $options['summaryID']=$this->summaryID;
  352. if($this->focus!==null)
  353. $options['focus']=$this->focus;
  354. $options=CJavaScript::encode($options);
  355. $cs->registerCoreScript('yiiactiveform');
  356. $id=$this->id;
  357. $cs->registerScript(__CLASS__.'#'.$id,"\$('#$id').yiiactiveform($options);");
  358. }
  359. /**
  360. * Displays the first validation error for a model attribute.
  361. * This is similar to {@link CHtml::error} except that it registers the model attribute
  362. * so that if its value is changed by users, an AJAX validation may be triggered.
  363. * @param CModel $model the data model
  364. * @param string $attribute the attribute name
  365. * @param array $htmlOptions additional HTML attributes to be rendered in the container div tag.
  366. * Besides all those options available in {@link CHtml::error}, the following options are recognized in addition:
  367. * <ul>
  368. * <li>validationDelay</li>
  369. * <li>validateOnChange</li>
  370. * <li>validateOnType</li>
  371. * <li>hideErrorMessage</li>
  372. * <li>inputContainer</li>
  373. * <li>errorCssClass</li>
  374. * <li>successCssClass</li>
  375. * <li>validatingCssClass</li>
  376. * <li>beforeValidateAttribute</li>
  377. * <li>afterValidateAttribute</li>
  378. * </ul>
  379. * These options override the corresponding options as declared in {@link options} for this
  380. * particular model attribute. For more details about these options, please refer to {@link clientOptions}.
  381. * Note that these options are only used when {@link enableAjaxValidation} or {@link enableClientValidation}
  382. * is set true.
  383. *
  384. * When client-side validation is enabled, an option named "clientValidation" is also recognized.
  385. * This option should take a piece of JavaScript code to perform client-side validation. In the code,
  386. * the variables are predefined:
  387. * <ul>
  388. * <li>value: the current input value associated with this attribute.</li>
  389. * <li>messages: an array that may be appended with new error messages for the attribute.</li>
  390. * <li>attribute: a data structure keeping all client-side options for the attribute</li>
  391. * </ul>
  392. * @param boolean $enableAjaxValidation whether to enable AJAX validation for the specified attribute.
  393. * Note that in order to enable AJAX validation, both {@link enableAjaxValidation} and this parameter
  394. * must be true.
  395. * @param boolean $enableClientValidation whether to enable client-side validation for the specified attribute.
  396. * Note that in order to enable client-side validation, both {@link enableClientValidation} and this parameter
  397. * must be true. This parameter has been available since version 1.1.7.
  398. * @return string the validation result (error display or success message).
  399. * @see CHtml::error
  400. */
  401. public function error($model,$attribute,$htmlOptions=array(),$enableAjaxValidation=true,$enableClientValidation=true)
  402. {
  403. if(!$this->enableAjaxValidation)
  404. $enableAjaxValidation=false;
  405. if(!$this->enableClientValidation)
  406. $enableClientValidation=false;
  407. if(!isset($htmlOptions['class']))
  408. $htmlOptions['class']=$this->errorMessageCssClass;
  409. if(!$enableAjaxValidation && !$enableClientValidation)
  410. return CHtml::error($model,$attribute,$htmlOptions);
  411. $id=CHtml::activeId($model,$attribute);
  412. $inputID=isset($htmlOptions['inputID']) ? $htmlOptions['inputID'] : $id;
  413. unset($htmlOptions['inputID']);
  414. if(!isset($htmlOptions['id']))
  415. $htmlOptions['id']=$inputID.'_em_';
  416. $option=array(
  417. 'id'=>$id,
  418. 'inputID'=>$inputID,
  419. 'errorID'=>$htmlOptions['id'],
  420. 'model'=>get_class($model),
  421. 'name'=>CHtml::resolveName($model, $attribute),
  422. 'enableAjaxValidation'=>$enableAjaxValidation,
  423. );
  424. $optionNames=array(
  425. 'validationDelay',
  426. 'validateOnChange',
  427. 'validateOnType',
  428. 'hideErrorMessage',
  429. 'inputContainer',
  430. 'errorCssClass',
  431. 'successCssClass',
  432. 'validatingCssClass',
  433. 'beforeValidateAttribute',
  434. 'afterValidateAttribute',
  435. );
  436. foreach($optionNames as $name)
  437. {
  438. if(isset($htmlOptions[$name]))
  439. {
  440. $option[$name]=$htmlOptions[$name];
  441. unset($htmlOptions[$name]);
  442. }
  443. }
  444. if($model instanceof CActiveRecord && !$model->isNewRecord)
  445. $option['status']=1;
  446. if($enableClientValidation)
  447. {
  448. $validators=isset($htmlOptions['clientValidation']) ? array($htmlOptions['clientValidation']) : array();
  449. foreach($model->getValidators($attribute) as $validator)
  450. {
  451. if($enableClientValidation && $validator->enableClientValidation)
  452. {
  453. if(($js=$validator->clientValidateAttribute($model,$attribute))!='')
  454. $validators[]=$js;
  455. }
  456. }
  457. if($validators!==array())
  458. $option['clientValidation']="js:function(value, messages, attribute) {\n".implode("\n",$validators)."\n}";
  459. }
  460. $html=CHtml::error($model,$attribute,$htmlOptions);
  461. if($html==='')
  462. {
  463. if(isset($htmlOptions['style']))
  464. $htmlOptions['style']=rtrim($htmlOptions['style'],';').';display:none';
  465. else
  466. $htmlOptions['style']='display:none';
  467. $html=CHtml::tag('div',$htmlOptions,'');
  468. }
  469. $this->attributes[$inputID]=$option;
  470. return $html;
  471. }
  472. /**
  473. * Displays a summary of validation errors for one or several models.
  474. * This method is very similar to {@link CHtml::errorSummary} except that it also works
  475. * when AJAX validation is performed.
  476. * @param mixed $models the models whose input errors are to be displayed. This can be either
  477. * a single model or an array of models.
  478. * @param string $header a piece of HTML code that appears in front of the errors
  479. * @param string $footer a piece of HTML code that appears at the end of the errors
  480. * @param array $htmlOptions additional HTML attributes to be rendered in the container div tag.
  481. * @return string the error summary. Empty if no errors are found.
  482. * @see CHtml::errorSummary
  483. */
  484. public function errorSummary($models,$header=null,$footer=null,$htmlOptions=array())
  485. {
  486. if(!$this->enableAjaxValidation && !$this->enableClientValidation)
  487. return CHtml::errorSummary($models,$header,$footer,$htmlOptions);
  488. if(!isset($htmlOptions['id']))
  489. $htmlOptions['id']=$this->id.'_es_';
  490. $html=CHtml::errorSummary($models,$header,$footer,$htmlOptions);
  491. if($html==='')
  492. {
  493. if($header===null)
  494. $header='<p>'.Yii::t('yii','Please fix the following input errors:').'</p>';
  495. if(!isset($htmlOptions['class']))
  496. $htmlOptions['class']=CHtml::$errorSummaryCss;
  497. $htmlOptions['style']=isset($htmlOptions['style']) ? rtrim($htmlOptions['style'],';').';display:none' : 'display:none';
  498. $html=CHtml::tag('div',$htmlOptions,$header."\n<ul><li>dummy</li></ul>".$footer);
  499. }
  500. $this->summaryID=$htmlOptions['id'];
  501. return $html;
  502. }
  503. /**
  504. * Renders an HTML label for a model attribute.
  505. * This method is a wrapper of {@link CHtml::activeLabel}.
  506. * Please check {@link CHtml::activeLabel} for detailed information
  507. * about the parameters for this method.
  508. * @param CModel $model the data model
  509. * @param string $attribute the attribute
  510. * @param array $htmlOptions additional HTML attributes.
  511. * @return string the generated label tag
  512. */
  513. public function label($model,$attribute,$htmlOptions=array())
  514. {
  515. return CHtml::activeLabel($model,$attribute,$htmlOptions);
  516. }
  517. /**
  518. * Renders an HTML label for a model attribute.
  519. * This method is a wrapper of {@link CHtml::activeLabelEx}.
  520. * Please check {@link CHtml::activeLabelEx} for detailed information
  521. * about the parameters for this method.
  522. * @param CModel $model the data model
  523. * @param string $attribute the attribute
  524. * @param array $htmlOptions additional HTML attributes.
  525. * @return string the generated label tag
  526. */
  527. public function labelEx($model,$attribute,$htmlOptions=array())
  528. {
  529. return CHtml::activeLabelEx($model,$attribute,$htmlOptions);
  530. }
  531. /**
  532. * Renders a text field for a model attribute.
  533. * This method is a wrapper of {@link CHtml::activeTextField}.
  534. * Please check {@link CHtml::activeTextField} for detailed information
  535. * about the parameters for this method.
  536. * @param CModel $model the data model
  537. * @param string $attribute the attribute
  538. * @param array $htmlOptions additional HTML attributes.
  539. * @return string the generated input field
  540. */
  541. public function textField($model,$attribute,$htmlOptions=array())
  542. {
  543. return CHtml::activeTextField($model,$attribute,$htmlOptions);
  544. }
  545. /**
  546. * Renders a hidden field for a model attribute.
  547. * This method is a wrapper of {@link CHtml::activeHiddenField}.
  548. * Please check {@link CHtml::activeHiddenField} for detailed information
  549. * about the parameters for this method.
  550. * @param CModel $model the data model
  551. * @param string $attribute the attribute
  552. * @param array $htmlOptions additional HTML attributes.
  553. * @return string the generated input field
  554. */
  555. public function hiddenField($model,$attribute,$htmlOptions=array())
  556. {
  557. return CHtml::activeHiddenField($model,$attribute,$htmlOptions);
  558. }
  559. /**
  560. * Renders a password field for a model attribute.
  561. * This method is a wrapper of {@link CHtml::activePasswordField}.
  562. * Please check {@link CHtml::activePasswordField} for detailed information
  563. * about the parameters for this method.
  564. * @param CModel $model the data model
  565. * @param string $attribute the attribute
  566. * @param array $htmlOptions additional HTML attributes.
  567. * @return string the generated input field
  568. */
  569. public function passwordField($model,$attribute,$htmlOptions=array())
  570. {
  571. return CHtml::activePasswordField($model,$attribute,$htmlOptions);
  572. }
  573. /**
  574. * Renders a text area for a model attribute.
  575. * This method is a wrapper of {@link CHtml::activeTextArea}.
  576. * Please check {@link CHtml::activeTextArea} for detailed information
  577. * about the parameters for this method.
  578. * @param CModel $model the data model
  579. * @param string $attribute the attribute
  580. * @param array $htmlOptions additional HTML attributes.
  581. * @return string the generated text area
  582. */
  583. public function textArea($model,$attribute,$htmlOptions=array())
  584. {
  585. return CHtml::activeTextArea($model,$attribute,$htmlOptions);
  586. }
  587. /**
  588. * Renders a file field for a model attribute.
  589. * This method is a wrapper of {@link CHtml::activeFileField}.
  590. * Please check {@link CHtml::activeFileField} for detailed information
  591. * about the parameters for this method.
  592. * @param CModel $model the data model
  593. * @param string $attribute the attribute
  594. * @param array $htmlOptions additional HTML attributes
  595. * @return string the generated input field
  596. */
  597. public function fileField($model,$attribute,$htmlOptions=array())
  598. {
  599. return CHtml::activeFileField($model,$attribute,$htmlOptions);
  600. }
  601. /**
  602. * Renders a radio button for a model attribute.
  603. * This method is a wrapper of {@link CHtml::activeRadioButton}.
  604. * Please check {@link CHtml::activeRadioButton} for detailed information
  605. * about the parameters for this method.
  606. * @param CModel $model the data model
  607. * @param string $attribute the attribute
  608. * @param array $htmlOptions additional HTML attributes.
  609. * @return string the generated radio button
  610. */
  611. public function radioButton($model,$attribute,$htmlOptions=array())
  612. {
  613. return CHtml::activeRadioButton($model,$attribute,$htmlOptions);
  614. }
  615. /**
  616. * Renders a checkbox for a model attribute.
  617. * This method is a wrapper of {@link CHtml::activeCheckBox}.
  618. * Please check {@link CHtml::activeCheckBox} for detailed information
  619. * about the parameters for this method.
  620. * @param CModel $model the data model
  621. * @param string $attribute the attribute
  622. * @param array $htmlOptions additional HTML attributes.
  623. * @return string the generated check box
  624. */
  625. public function checkBox($model,$attribute,$htmlOptions=array())
  626. {
  627. return CHtml::activeCheckBox($model,$attribute,$htmlOptions);
  628. }
  629. /**
  630. * Renders a dropdown list for a model attribute.
  631. * This method is a wrapper of {@link CHtml::activeDropDownList}.
  632. * Please check {@link CHtml::activeDropDownList} for detailed information
  633. * about the parameters for this method.
  634. * @param CModel $model the data model
  635. * @param string $attribute the attribute
  636. * @param array $data data for generating the list options (value=>display)
  637. * @param array $htmlOptions additional HTML attributes.
  638. * @return string the generated drop down list
  639. */
  640. public function dropDownList($model,$attribute,$data,$htmlOptions=array())
  641. {
  642. return CHtml::activeDropDownList($model,$attribute,$data,$htmlOptions);
  643. }
  644. /**
  645. * Renders a list box for a model attribute.
  646. * This method is a wrapper of {@link CHtml::activeListBox}.
  647. * Please check {@link CHtml::activeListBox} for detailed information
  648. * about the parameters for this method.
  649. * @param CModel $model the data model
  650. * @param string $attribute the attribute
  651. * @param array $data data for generating the list options (value=>display)
  652. * @param array $htmlOptions additional HTML attributes.
  653. * @return string the generated list box
  654. */
  655. public function listBox($model,$attribute,$data,$htmlOptions=array())
  656. {
  657. return CHtml::activeListBox($model,$attribute,$data,$htmlOptions);
  658. }
  659. /**
  660. * Renders a checkbox list for a model attribute.
  661. * This method is a wrapper of {@link CHtml::activeCheckBoxList}.
  662. * Please check {@link CHtml::activeCheckBoxList} for detailed information
  663. * about the parameters for this method.
  664. * @param CModel $model the data model
  665. * @param string $attribute the attribute
  666. * @param array $data value-label pairs used to generate the check box list.
  667. * @param array $htmlOptions addtional HTML options.
  668. * @return string the generated check box list
  669. */
  670. public function checkBoxList($model,$attribute,$data,$htmlOptions=array())
  671. {
  672. return CHtml::activeCheckBoxList($model,$attribute,$data,$htmlOptions);
  673. }
  674. /**
  675. * Renders a radio button list for a model attribute.
  676. * This method is a wrapper of {@link CHtml::activeRadioButtonList}.
  677. * Please check {@link CHtml::activeRadioButtonList} for detailed information
  678. * about the parameters for this method.
  679. * @param CModel $model the data model
  680. * @param string $attribute the attribute
  681. * @param array $data value-label pairs used to generate the radio button list.
  682. * @param array $htmlOptions addtional HTML options.
  683. * @return string the generated radio button list
  684. */
  685. public function radioButtonList($model,$attribute,$data,$htmlOptions=array())
  686. {
  687. return CHtml::activeRadioButtonList($model,$attribute,$data,$htmlOptions);
  688. }
  689. /**
  690. * Validates one or several models and returns the results in JSON format.
  691. * This is a helper method that simplifies the way of writing AJAX validation code.
  692. * @param mixed $models a single model instance or an array of models.
  693. * @param array $attributes list of attributes that should be validated. Defaults to null,
  694. * meaning any attribute listed in the applicable validation rules of the models should be
  695. * validated. If this parameter is given as a list of attributes, only
  696. * the listed attributes will be validated.
  697. * @param boolean $loadInput whether to load the data from $_POST array in this method.
  698. * If this is true, the model will be populated from <code>$_POST[ModelClass]</code>.
  699. * @return string the JSON representation of the validation error messages.
  700. */
  701. public static function validate($models, $attributes=null, $loadInput=true)
  702. {
  703. $result=array();
  704. if(!is_array($models))
  705. $models=array($models);
  706. foreach($models as $model)
  707. {
  708. if($loadInput && isset($_POST[get_class($model)]))
  709. $model->attributes=$_POST[get_class($model)];
  710. $model->validate($attributes);
  711. foreach($model->getErrors() as $attribute=>$errors)
  712. $result[CHtml::activeId($model,$attribute)]=$errors;
  713. }
  714. return function_exists('json_encode') ? json_encode($result) : CJSON::encode($result);
  715. }
  716. }