CActiveForm.php 42 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022
  1. <?php
  2. /**
  3. * CActiveForm class file.
  4. *
  5. * @author Qiang Xue <qiang.xue@gmail.com>
  6. * @link http://www.yiiframework.com/
  7. * @copyright 2008-2013 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. * @package system.web.widgets
  144. * @since 1.1.1
  145. */
  146. class CActiveForm extends CWidget
  147. {
  148. /**
  149. * @var mixed the form action URL (see {@link CHtml::normalizeUrl} for details about this parameter).
  150. * If not set, the current page URL is used.
  151. */
  152. public $action='';
  153. /**
  154. * @var string the form submission method. This should be either 'post' or 'get'.
  155. * Defaults to 'post'.
  156. */
  157. public $method='post';
  158. /**
  159. * @var boolean whether to generate a stateful form (See {@link CHtml::statefulForm}). Defaults to false.
  160. */
  161. public $stateful=false;
  162. /**
  163. * @var string the CSS class name for error messages.
  164. * Since 1.1.14 this defaults to 'errorMessage' defined in {@link CHtml::$errorMessageCss}.
  165. * Individual {@link error} call may override this value by specifying the 'class' HTML option.
  166. */
  167. public $errorMessageCssClass;
  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 wrap the value with {@link CJavaScriptExpression} 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 wrap the value with {@link CJavaScriptExpression} 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 wrap the value with {@link CJavaScriptExpression} 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>afterValidateAttribute(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 wrap the value with {@link CJavaScriptExpression} 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. * @var string[] attribute IDs to be used to display error summary.
  313. * @since 1.1.14
  314. */
  315. private $_summaryAttributes=array();
  316. /**
  317. * Initializes the widget.
  318. * This renders the form open tag.
  319. */
  320. public function init()
  321. {
  322. if(!isset($this->htmlOptions['id']))
  323. $this->htmlOptions['id']=$this->id;
  324. else
  325. $this->id=$this->htmlOptions['id'];
  326. if($this->stateful)
  327. echo CHtml::statefulForm($this->action, $this->method, $this->htmlOptions);
  328. else
  329. echo CHtml::beginForm($this->action, $this->method, $this->htmlOptions);
  330. if($this->errorMessageCssClass===null)
  331. $this->errorMessageCssClass=CHtml::$errorMessageCss;
  332. }
  333. /**
  334. * Runs the widget.
  335. * This registers the necessary javascript code and renders the form close tag.
  336. */
  337. public function run()
  338. {
  339. if(is_array($this->focus))
  340. $this->focus="#".CHtml::activeId($this->focus[0],$this->focus[1]);
  341. echo CHtml::endForm();
  342. $cs=Yii::app()->clientScript;
  343. if(!$this->enableAjaxValidation && !$this->enableClientValidation || empty($this->attributes))
  344. {
  345. if($this->focus!==null)
  346. {
  347. $cs->registerCoreScript('jquery');
  348. $cs->registerScript('CActiveForm#focus',"
  349. if(!window.location.hash)
  350. jQuery('".$this->focus."').focus();
  351. ");
  352. }
  353. return;
  354. }
  355. $options=$this->clientOptions;
  356. if(isset($this->clientOptions['validationUrl']) && is_array($this->clientOptions['validationUrl']))
  357. $options['validationUrl']=CHtml::normalizeUrl($this->clientOptions['validationUrl']);
  358. foreach($this->_summaryAttributes as $attribute)
  359. $this->attributes[$attribute]['summary']=true;
  360. $options['attributes']=array_values($this->attributes);
  361. if($this->summaryID!==null)
  362. $options['summaryID']=$this->summaryID;
  363. if($this->focus!==null)
  364. $options['focus']=$this->focus;
  365. if(!empty(CHtml::$errorCss))
  366. $options['errorCss']=CHtml::$errorCss;
  367. $options=CJavaScript::encode($options);
  368. $cs->registerCoreScript('yiiactiveform');
  369. $id=$this->id;
  370. $cs->registerScript(__CLASS__.'#'.$id,"jQuery('#$id').yiiactiveform($options);");
  371. }
  372. /**
  373. * Displays the first validation error for a model attribute.
  374. * This is similar to {@link CHtml::error} except that it registers the model attribute
  375. * so that if its value is changed by users, an AJAX validation may be triggered.
  376. * @param CModel $model the data model
  377. * @param string $attribute the attribute name
  378. * @param array $htmlOptions additional HTML attributes to be rendered in the container div tag.
  379. * Besides all those options available in {@link CHtml::error}, the following options are recognized in addition:
  380. * <ul>
  381. * <li>validationDelay</li>
  382. * <li>validateOnChange</li>
  383. * <li>validateOnType</li>
  384. * <li>hideErrorMessage</li>
  385. * <li>inputContainer</li>
  386. * <li>errorCssClass</li>
  387. * <li>successCssClass</li>
  388. * <li>validatingCssClass</li>
  389. * <li>beforeValidateAttribute</li>
  390. * <li>afterValidateAttribute</li>
  391. * </ul>
  392. * These options override the corresponding options as declared in {@link options} for this
  393. * particular model attribute. For more details about these options, please refer to {@link clientOptions}.
  394. * Note that these options are only used when {@link enableAjaxValidation} or {@link enableClientValidation}
  395. * is set true.
  396. * <ul>
  397. * <li>inputID</li>
  398. * </ul>
  399. * When an CActiveForm input field uses a custom ID, for ajax/client validation to work properly
  400. * inputID should be set to the same ID
  401. *
  402. * Example:
  403. * <pre>
  404. * <div class="form-element">
  405. * <?php echo $form->labelEx($model,'attribute'); ?>
  406. * <?php echo $form->textField($model,'attribute', array('id'=>'custom-id')); ?>
  407. * <?php echo $form->error($model,'attribute',array('inputID'=>'custom-id')); ?>
  408. * </div>
  409. * </pre>
  410. *
  411. * When client-side validation is enabled, an option named "clientValidation" is also recognized.
  412. * This option should take a piece of JavaScript code to perform client-side validation. In the code,
  413. * the variables are predefined:
  414. * <ul>
  415. * <li>value: the current input value associated with this attribute.</li>
  416. * <li>messages: an array that may be appended with new error messages for the attribute.</li>
  417. * <li>attribute: a data structure keeping all client-side options for the attribute</li>
  418. * </ul>
  419. * This should NOT be a function but just the code, Yii will enclose the code you provide inside the
  420. * actual JS function.
  421. * @param boolean $enableAjaxValidation whether to enable AJAX validation for the specified attribute.
  422. * Note that in order to enable AJAX validation, both {@link enableAjaxValidation} and this parameter
  423. * must be true.
  424. * @param boolean $enableClientValidation whether to enable client-side validation for the specified attribute.
  425. * Note that in order to enable client-side validation, both {@link enableClientValidation} and this parameter
  426. * must be true. This parameter has been available since version 1.1.7.
  427. * @return string the validation result (error display or success message).
  428. * @see CHtml::error
  429. */
  430. public function error($model,$attribute,$htmlOptions=array(),$enableAjaxValidation=true,$enableClientValidation=true)
  431. {
  432. if(!$this->enableAjaxValidation)
  433. $enableAjaxValidation=false;
  434. if(!$this->enableClientValidation)
  435. $enableClientValidation=false;
  436. if(!isset($htmlOptions['class']))
  437. $htmlOptions['class']=$this->errorMessageCssClass;
  438. if(!$enableAjaxValidation && !$enableClientValidation)
  439. return CHtml::error($model,$attribute,$htmlOptions);
  440. $id=CHtml::activeId($model,$attribute);
  441. $inputID=isset($htmlOptions['inputID']) ? $htmlOptions['inputID'] : $id;
  442. unset($htmlOptions['inputID']);
  443. if(!isset($htmlOptions['id']))
  444. $htmlOptions['id']=$inputID.'_em_';
  445. $option=array(
  446. 'id'=>$id,
  447. 'inputID'=>$inputID,
  448. 'errorID'=>$htmlOptions['id'],
  449. 'model'=>get_class($model),
  450. 'name'=>$attribute,
  451. 'enableAjaxValidation'=>$enableAjaxValidation,
  452. );
  453. $optionNames=array(
  454. 'validationDelay',
  455. 'validateOnChange',
  456. 'validateOnType',
  457. 'hideErrorMessage',
  458. 'inputContainer',
  459. 'errorCssClass',
  460. 'successCssClass',
  461. 'validatingCssClass',
  462. 'beforeValidateAttribute',
  463. 'afterValidateAttribute',
  464. );
  465. foreach($optionNames as $name)
  466. {
  467. if(isset($htmlOptions[$name]))
  468. {
  469. $option[$name]=$htmlOptions[$name];
  470. unset($htmlOptions[$name]);
  471. }
  472. }
  473. if($model instanceof CActiveRecord && !$model->isNewRecord)
  474. $option['status']=1;
  475. if($enableClientValidation)
  476. {
  477. $validators=isset($htmlOptions['clientValidation']) ? array($htmlOptions['clientValidation']) : array();
  478. unset($htmlOptions['clientValidation']);
  479. $attributeName = $attribute;
  480. if(($pos=strrpos($attribute,']'))!==false && $pos!==strlen($attribute)-1) // e.g. [a]name
  481. {
  482. $attributeName=substr($attribute,$pos+1);
  483. }
  484. foreach($model->getValidators($attributeName) as $validator)
  485. {
  486. if($validator->enableClientValidation)
  487. {
  488. if(($js=$validator->clientValidateAttribute($model,$attributeName))!='')
  489. $validators[]=$js;
  490. }
  491. }
  492. if($validators!==array())
  493. $option['clientValidation']=new CJavaScriptExpression("function(value, messages, attribute) {\n".implode("\n",$validators)."\n}");
  494. }
  495. if(empty($option['hideErrorMessage']) && empty($this->clientOptions['hideErrorMessage']))
  496. $html=CHtml::error($model,$attribute,$htmlOptions);
  497. else
  498. $html='';
  499. if($html==='')
  500. {
  501. if(isset($htmlOptions['style']))
  502. $htmlOptions['style']=rtrim($htmlOptions['style'],';').';display:none';
  503. else
  504. $htmlOptions['style']='display:none';
  505. $html=CHtml::tag(CHtml::$errorContainerTag,$htmlOptions,'');
  506. }
  507. $this->attributes[$inputID]=$option;
  508. return $html;
  509. }
  510. /**
  511. * Displays a summary of validation errors for one or several models.
  512. * This method is very similar to {@link CHtml::errorSummary} except that it also works
  513. * when AJAX validation is performed.
  514. * @param mixed $models the models whose input errors are to be displayed. This can be either
  515. * a single model or an array of models.
  516. * @param string $header a piece of HTML code that appears in front of the errors
  517. * @param string $footer a piece of HTML code that appears at the end of the errors
  518. * @param array $htmlOptions additional HTML attributes to be rendered in the container div tag.
  519. * @return string the error summary. Empty if no errors are found.
  520. * @see CHtml::errorSummary
  521. */
  522. public function errorSummary($models,$header=null,$footer=null,$htmlOptions=array())
  523. {
  524. if(!$this->enableAjaxValidation && !$this->enableClientValidation)
  525. return CHtml::errorSummary($models,$header,$footer,$htmlOptions);
  526. if(!isset($htmlOptions['id']))
  527. $htmlOptions['id']=$this->id.'_es_';
  528. $html=CHtml::errorSummary($models,$header,$footer,$htmlOptions);
  529. if($html==='')
  530. {
  531. if($header===null)
  532. $header='<p>'.Yii::t('yii','Please fix the following input errors:').'</p>';
  533. if(!isset($htmlOptions['class']))
  534. $htmlOptions['class']=CHtml::$errorSummaryCss;
  535. $htmlOptions['style']=isset($htmlOptions['style']) ? rtrim($htmlOptions['style'],';').';display:none' : 'display:none';
  536. $html=CHtml::tag('div',$htmlOptions,$header."\n<ul><li>dummy</li></ul>".$footer);
  537. }
  538. $this->summaryID=$htmlOptions['id'];
  539. foreach(is_array($models) ? $models : array($models) as $model)
  540. foreach($model->getSafeAttributeNames() as $attribute)
  541. $this->_summaryAttributes[]=CHtml::activeId($model,$attribute);
  542. return $html;
  543. }
  544. /**
  545. * Renders an HTML label for a model attribute.
  546. * This method is a wrapper of {@link CHtml::activeLabel}.
  547. * Please check {@link CHtml::activeLabel} for detailed information
  548. * about the parameters for this method.
  549. * @param CModel $model the data model
  550. * @param string $attribute the attribute
  551. * @param array $htmlOptions additional HTML attributes.
  552. * @return string the generated label tag
  553. */
  554. public function label($model,$attribute,$htmlOptions=array())
  555. {
  556. return CHtml::activeLabel($model,$attribute,$htmlOptions);
  557. }
  558. /**
  559. * Renders an HTML label for a model attribute.
  560. * This method is a wrapper of {@link CHtml::activeLabelEx}.
  561. * Please check {@link CHtml::activeLabelEx} for detailed information
  562. * about the parameters for this method.
  563. * @param CModel $model the data model
  564. * @param string $attribute the attribute
  565. * @param array $htmlOptions additional HTML attributes.
  566. * @return string the generated label tag
  567. */
  568. public function labelEx($model,$attribute,$htmlOptions=array())
  569. {
  570. return CHtml::activeLabelEx($model,$attribute,$htmlOptions);
  571. }
  572. /**
  573. * Renders a url field for a model attribute.
  574. * This method is a wrapper of {@link CHtml::activeUrlField}.
  575. * Please check {@link CHtml::activeUrlField} for detailed information
  576. * about the parameters for this method.
  577. * @param CModel $model the data model
  578. * @param string $attribute the attribute
  579. * @param array $htmlOptions additional HTML attributes.
  580. * @return string the generated input field
  581. * @since 1.1.11
  582. */
  583. public function urlField($model,$attribute,$htmlOptions=array())
  584. {
  585. return CHtml::activeUrlField($model,$attribute,$htmlOptions);
  586. }
  587. /**
  588. * Renders an email field for a model attribute.
  589. * This method is a wrapper of {@link CHtml::activeEmailField}.
  590. * Please check {@link CHtml::activeEmailField} 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. * @since 1.1.11
  597. */
  598. public function emailField($model,$attribute,$htmlOptions=array())
  599. {
  600. return CHtml::activeEmailField($model,$attribute,$htmlOptions);
  601. }
  602. /**
  603. * Renders a number field for a model attribute.
  604. * This method is a wrapper of {@link CHtml::activeNumberField}.
  605. * Please check {@link CHtml::activeNumberField} for detailed information
  606. * about the parameters for this method.
  607. * @param CModel $model the data model
  608. * @param string $attribute the attribute
  609. * @param array $htmlOptions additional HTML attributes.
  610. * @return string the generated input field
  611. * @since 1.1.11
  612. */
  613. public function numberField($model,$attribute,$htmlOptions=array())
  614. {
  615. return CHtml::activeNumberField($model,$attribute,$htmlOptions);
  616. }
  617. /**
  618. * Generates a range field for a model attribute.
  619. * This method is a wrapper of {@link CHtml::activeRangeField}.
  620. * Please check {@link CHtml::activeRangeField} for detailed information
  621. * about the parameters for this method.
  622. * @param CModel $model the data model
  623. * @param string $attribute the attribute
  624. * @param array $htmlOptions additional HTML attributes.
  625. * @return string the generated input field
  626. * @since 1.1.11
  627. */
  628. public function rangeField($model,$attribute,$htmlOptions=array())
  629. {
  630. return CHtml::activeRangeField($model,$attribute,$htmlOptions);
  631. }
  632. /**
  633. * Renders a date field for a model attribute.
  634. * This method is a wrapper of {@link CHtml::activeDateField}.
  635. * Please check {@link CHtml::activeDateField} for detailed information
  636. * about the parameters for this method.
  637. * @param CModel $model the data model
  638. * @param string $attribute the attribute
  639. * @param array $htmlOptions additional HTML attributes.
  640. * @return string the generated input field
  641. * @since 1.1.11
  642. */
  643. public function dateField($model,$attribute,$htmlOptions=array())
  644. {
  645. return CHtml::activeDateField($model,$attribute,$htmlOptions);
  646. }
  647. /**
  648. * Renders a time field for a model attribute.
  649. * This method is a wrapper of {@link CHtml::activeTimeField}.
  650. * Please check {@link CHtml::activeTimeField} for detailed information
  651. * about the parameters for this method.
  652. * @param CModel $model the data model
  653. * @param string $attribute the attribute
  654. * @param array $htmlOptions additional HTML attributes.
  655. * @return string the generated input field
  656. * @since 1.1.14
  657. */
  658. public function timeField($model,$attribute,$htmlOptions=array())
  659. {
  660. return CHtml::activeTimeField($model,$attribute,$htmlOptions);
  661. }
  662. /**
  663. * Renders a datetime field for a model attribute.
  664. * This method is a wrapper of {@link CHtml::activeDateTimeField}.
  665. * Please check {@link CHtml::activeDateTimeField} for detailed information
  666. * about the parameters for this method.
  667. * @param CModel $model the data model
  668. * @param string $attribute the attribute
  669. * @param array $htmlOptions additional HTML attributes.
  670. * @return string the generated input field
  671. * @since 1.1.16
  672. */
  673. public function dateTimeField($model,$attribute,$htmlOptions=array())
  674. {
  675. return CHtml::activeDateTimeField($model,$attribute,$htmlOptions);
  676. }
  677. /**
  678. * Renders a local datetime field for a model attribute.
  679. * This method is a wrapper of {@link CHtml::activeDateTimeLocalField}.
  680. * Please check {@link CHtml::activeDateTimeLocalField} for detailed information
  681. * about the parameters for this method.
  682. * @param CModel $model the data model
  683. * @param string $attribute the attribute
  684. * @param array $htmlOptions additional HTML attributes.
  685. * @return string the generated input field
  686. * @since 1.1.16
  687. */
  688. public function dateTimeLocalField($model,$attribute,$htmlOptions=array())
  689. {
  690. return CHtml::activeDateTimeLocalField($model,$attribute,$htmlOptions);
  691. }
  692. /**
  693. * Renders a week field for a model attribute.
  694. * This method is a wrapper of {@link CHtml::activeWeekField}.
  695. * Please check {@link CHtml::activeWeekField} for detailed information
  696. * about the parameters for this method.
  697. * @param CModel $model the data model
  698. * @param string $attribute the attribute
  699. * @param array $htmlOptions additional HTML attributes.
  700. * @return string the generated input field
  701. * @since 1.1.16
  702. */
  703. public function weekField($model,$attribute,$htmlOptions=array())
  704. {
  705. return CHtml::activeWeekField($model,$attribute,$htmlOptions);
  706. }
  707. /**
  708. * Renders a color picker field for a model attribute.
  709. * This method is a wrapper of {@link CHtml::activeColorField}.
  710. * Please check {@link CHtml::activeColorField} for detailed information
  711. * about the parameters for this method.
  712. * @param CModel $model the data model
  713. * @param string $attribute the attribute
  714. * @param array $htmlOptions additional HTML attributes.
  715. * @return string the generated input field
  716. * @since 1.1.16
  717. */
  718. public function colorField($model,$attribute,$htmlOptions=array())
  719. {
  720. return CHtml::activeColorField($model,$attribute,$htmlOptions);
  721. }
  722. /**
  723. * Renders a tel field for a model attribute.
  724. * This method is a wrapper of {@link CHtml::activeTelField}.
  725. * Please check {@link CHtml::activeTelField} for detailed information
  726. * about the parameters for this method.
  727. * @param CModel $model the data model
  728. * @param string $attribute the attribute
  729. * @param array $htmlOptions additional HTML attributes.
  730. * @return string the generated input field
  731. * @since 1.1.14
  732. */
  733. public function telField($model,$attribute,$htmlOptions=array())
  734. {
  735. return CHtml::activeTelField($model,$attribute,$htmlOptions);
  736. }
  737. /**
  738. * Renders a text field for a model attribute.
  739. * This method is a wrapper of {@link CHtml::activeTextField}.
  740. * Please check {@link CHtml::activeTextField} for detailed information
  741. * about the parameters for this method.
  742. * @param CModel $model the data model
  743. * @param string $attribute the attribute
  744. * @param array $htmlOptions additional HTML attributes.
  745. * @return string the generated input field
  746. */
  747. public function textField($model,$attribute,$htmlOptions=array())
  748. {
  749. return CHtml::activeTextField($model,$attribute,$htmlOptions);
  750. }
  751. /**
  752. * Renders a search field for a model attribute.
  753. * This method is a wrapper of {@link CHtml::activeSearchField}.
  754. * Please check {@link CHtml::activeSearchField} for detailed information
  755. * about the parameters for this method.
  756. * @param CModel $model the data model
  757. * @param string $attribute the attribute
  758. * @param array $htmlOptions additional HTML attributes.
  759. * @return string the generated input field
  760. * @since 1.1.14
  761. */
  762. public function searchField($model,$attribute,$htmlOptions=array())
  763. {
  764. return CHtml::activeSearchField($model,$attribute,$htmlOptions);
  765. }
  766. /**
  767. * Renders a hidden field for a model attribute.
  768. * This method is a wrapper of {@link CHtml::activeHiddenField}.
  769. * Please check {@link CHtml::activeHiddenField} for detailed information
  770. * about the parameters for this method.
  771. * @param CModel $model the data model
  772. * @param string $attribute the attribute
  773. * @param array $htmlOptions additional HTML attributes.
  774. * @return string the generated input field
  775. */
  776. public function hiddenField($model,$attribute,$htmlOptions=array())
  777. {
  778. return CHtml::activeHiddenField($model,$attribute,$htmlOptions);
  779. }
  780. /**
  781. * Renders a password field for a model attribute.
  782. * This method is a wrapper of {@link CHtml::activePasswordField}.
  783. * Please check {@link CHtml::activePasswordField} for detailed information
  784. * about the parameters for this method.
  785. * @param CModel $model the data model
  786. * @param string $attribute the attribute
  787. * @param array $htmlOptions additional HTML attributes.
  788. * @return string the generated input field
  789. */
  790. public function passwordField($model,$attribute,$htmlOptions=array())
  791. {
  792. return CHtml::activePasswordField($model,$attribute,$htmlOptions);
  793. }
  794. /**
  795. * Renders a text area for a model attribute.
  796. * This method is a wrapper of {@link CHtml::activeTextArea}.
  797. * Please check {@link CHtml::activeTextArea} for detailed information
  798. * about the parameters for this method.
  799. * @param CModel $model the data model
  800. * @param string $attribute the attribute
  801. * @param array $htmlOptions additional HTML attributes.
  802. * @return string the generated text area
  803. */
  804. public function textArea($model,$attribute,$htmlOptions=array())
  805. {
  806. return CHtml::activeTextArea($model,$attribute,$htmlOptions);
  807. }
  808. /**
  809. * Renders a file field for a model attribute.
  810. * This method is a wrapper of {@link CHtml::activeFileField}.
  811. * Please check {@link CHtml::activeFileField} for detailed information
  812. * about the parameters for this method.
  813. * @param CModel $model the data model
  814. * @param string $attribute the attribute
  815. * @param array $htmlOptions additional HTML attributes
  816. * @return string the generated input field
  817. */
  818. public function fileField($model,$attribute,$htmlOptions=array())
  819. {
  820. return CHtml::activeFileField($model,$attribute,$htmlOptions);
  821. }
  822. /**
  823. * Renders a radio button for a model attribute.
  824. * This method is a wrapper of {@link CHtml::activeRadioButton}.
  825. * Please check {@link CHtml::activeRadioButton} for detailed information
  826. * about the parameters for this method.
  827. * @param CModel $model the data model
  828. * @param string $attribute the attribute
  829. * @param array $htmlOptions additional HTML attributes.
  830. * @return string the generated radio button
  831. */
  832. public function radioButton($model,$attribute,$htmlOptions=array())
  833. {
  834. return CHtml::activeRadioButton($model,$attribute,$htmlOptions);
  835. }
  836. /**
  837. * Renders a checkbox for a model attribute.
  838. * This method is a wrapper of {@link CHtml::activeCheckBox}.
  839. * Please check {@link CHtml::activeCheckBox} for detailed information
  840. * about the parameters for this method.
  841. * @param CModel $model the data model
  842. * @param string $attribute the attribute
  843. * @param array $htmlOptions additional HTML attributes.
  844. * @return string the generated check box
  845. */
  846. public function checkBox($model,$attribute,$htmlOptions=array())
  847. {
  848. return CHtml::activeCheckBox($model,$attribute,$htmlOptions);
  849. }
  850. /**
  851. * Renders a dropdown list for a model attribute.
  852. * This method is a wrapper of {@link CHtml::activeDropDownList}.
  853. * Please check {@link CHtml::activeDropDownList} for detailed information
  854. * about the parameters for this method.
  855. * @param CModel $model the data model
  856. * @param string $attribute the attribute
  857. * @param array $data data for generating the list options (value=>display)
  858. * @param array $htmlOptions additional HTML attributes.
  859. * @return string the generated drop down list
  860. */
  861. public function dropDownList($model,$attribute,$data,$htmlOptions=array())
  862. {
  863. return CHtml::activeDropDownList($model,$attribute,$data,$htmlOptions);
  864. }
  865. /**
  866. * Renders a list box for a model attribute.
  867. * This method is a wrapper of {@link CHtml::activeListBox}.
  868. * Please check {@link CHtml::activeListBox} for detailed information
  869. * about the parameters for this method.
  870. * @param CModel $model the data model
  871. * @param string $attribute the attribute
  872. * @param array $data data for generating the list options (value=>display)
  873. * @param array $htmlOptions additional HTML attributes.
  874. * @return string the generated list box
  875. */
  876. public function listBox($model,$attribute,$data,$htmlOptions=array())
  877. {
  878. return CHtml::activeListBox($model,$attribute,$data,$htmlOptions);
  879. }
  880. /**
  881. * Renders a checkbox list for a model attribute.
  882. * This method is a wrapper of {@link CHtml::activeCheckBoxList}.
  883. * Please check {@link CHtml::activeCheckBoxList} for detailed information
  884. * about the parameters for this method.
  885. * @param CModel $model the data model
  886. * @param string $attribute the attribute
  887. * @param array $data value-label pairs used to generate the check box list.
  888. * @param array $htmlOptions addtional HTML options.
  889. * @return string the generated check box list
  890. */
  891. public function checkBoxList($model,$attribute,$data,$htmlOptions=array())
  892. {
  893. return CHtml::activeCheckBoxList($model,$attribute,$data,$htmlOptions);
  894. }
  895. /**
  896. * Renders a radio button list for a model attribute.
  897. * This method is a wrapper of {@link CHtml::activeRadioButtonList}.
  898. * Please check {@link CHtml::activeRadioButtonList} for detailed information
  899. * about the parameters for this method.
  900. * @param CModel $model the data model
  901. * @param string $attribute the attribute
  902. * @param array $data value-label pairs used to generate the radio button list.
  903. * @param array $htmlOptions addtional HTML options.
  904. * @return string the generated radio button list
  905. */
  906. public function radioButtonList($model,$attribute,$data,$htmlOptions=array())
  907. {
  908. return CHtml::activeRadioButtonList($model,$attribute,$data,$htmlOptions);
  909. }
  910. /**
  911. * Validates one or several models and returns the results in JSON format.
  912. * This is a helper method that simplifies the way of writing AJAX validation code.
  913. * @param mixed $models a single model instance or an array of models.
  914. * @param array $attributes list of attributes that should be validated. Defaults to null,
  915. * meaning any attribute listed in the applicable validation rules of the models should be
  916. * validated. If this parameter is given as a list of attributes, only
  917. * the listed attributes will be validated.
  918. * @param boolean $loadInput whether to load the data from $_POST array in this method.
  919. * If this is true, the model will be populated from <code>$_POST[ModelClass]</code>.
  920. * @return string the JSON representation of the validation error messages.
  921. */
  922. public static function validate($models, $attributes=null, $loadInput=true)
  923. {
  924. $result=array();
  925. if(!is_array($models))
  926. $models=array($models);
  927. foreach($models as $model)
  928. {
  929. $modelName=CHtml::modelName($model);
  930. if($loadInput && isset($_POST[$modelName]))
  931. $model->attributes=$_POST[$modelName];
  932. $model->validate($attributes);
  933. foreach($model->getErrors() as $attribute=>$errors)
  934. $result[CHtml::activeId($model,$attribute)]=$errors;
  935. }
  936. return function_exists('json_encode') ? json_encode($result) : CJSON::encode($result);
  937. }
  938. /**
  939. * Validates an array of model instances and returns the results in JSON format.
  940. * This is a helper method that simplifies the way of writing AJAX validation code for tabular input.
  941. * @param mixed $models an array of model instances.
  942. * @param array $attributes list of attributes that should be validated. Defaults to null,
  943. * meaning any attribute listed in the applicable validation rules of the models should be
  944. * validated. If this parameter is given as a list of attributes, only
  945. * the listed attributes will be validated.
  946. * @param boolean $loadInput whether to load the data from $_POST array in this method.
  947. * If this is true, the model will be populated from <code>$_POST[ModelClass][$i]</code>.
  948. * @return string the JSON representation of the validation error messages.
  949. */
  950. public static function validateTabular($models, $attributes=null, $loadInput=true)
  951. {
  952. $result=array();
  953. if(!is_array($models))
  954. $models=array($models);
  955. foreach($models as $i=>$model)
  956. {
  957. $modelName=CHtml::modelName($model);
  958. if($loadInput && isset($_POST[$modelName][$i]))
  959. $model->attributes=$_POST[$modelName][$i];
  960. $model->validate($attributes);
  961. foreach($model->getErrors() as $attribute=>$errors)
  962. $result[CHtml::activeId($model,'['.$i.']'.$attribute)]=$errors;
  963. }
  964. return function_exists('json_encode') ? json_encode($result) : CJSON::encode($result);
  965. }
  966. }