ActiveForm.php 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464
  1. <?php
  2. /**
  3. * @link http://www.yiiframework.com/
  4. * @copyright Copyright (c) 2008 Yii Software LLC
  5. * @license http://www.yiiframework.com/license/
  6. */
  7. namespace yii\widgets;
  8. use Yii;
  9. use yii\base\InvalidCallException;
  10. use yii\base\Model;
  11. use yii\base\Widget;
  12. use yii\helpers\ArrayHelper;
  13. use yii\helpers\Html;
  14. use yii\helpers\Json;
  15. use yii\helpers\Url;
  16. /**
  17. * ActiveForm is a widget that builds an interactive HTML form for one or multiple data models.
  18. *
  19. * For more details and usage information on ActiveForm, see the [guide article on forms](guide:input-forms).
  20. *
  21. * @author Qiang Xue <qiang.xue@gmail.com>
  22. * @since 2.0
  23. */
  24. class ActiveForm extends Widget
  25. {
  26. /**
  27. * Add validation state class to container tag
  28. * @since 2.0.14
  29. */
  30. const VALIDATION_STATE_ON_CONTAINER = 'container';
  31. /**
  32. * Add validation state class to input tag
  33. * @since 2.0.14
  34. */
  35. const VALIDATION_STATE_ON_INPUT = 'input';
  36. /**
  37. * @var array|string the form action URL. This parameter will be processed by [[\yii\helpers\Url::to()]].
  38. * @see method for specifying the HTTP method for this form.
  39. */
  40. public $action = '';
  41. /**
  42. * @var string the form submission method. This should be either `post` or `get`. Defaults to `post`.
  43. *
  44. * When you set this to `get` you may see the url parameters repeated on each request.
  45. * This is because the default value of [[action]] is set to be the current request url and each submit
  46. * will add new parameters instead of replacing existing ones.
  47. * You may set [[action]] explicitly to avoid this:
  48. *
  49. * ```php
  50. * $form = ActiveForm::begin([
  51. * 'method' => 'get',
  52. * 'action' => ['controller/action'],
  53. * ]);
  54. * ```
  55. */
  56. public $method = 'post';
  57. /**
  58. * @var array the HTML attributes (name-value pairs) for the form tag.
  59. * @see \yii\helpers\Html::renderTagAttributes() for details on how attributes are being rendered.
  60. */
  61. public $options = [];
  62. /**
  63. * @var string the default field class name when calling [[field()]] to create a new field.
  64. * @see fieldConfig
  65. */
  66. public $fieldClass = 'yii\widgets\ActiveField';
  67. /**
  68. * @var array|\Closure the default configuration used by [[field()]] when creating a new field object.
  69. * This can be either a configuration array or an anonymous function returning a configuration array.
  70. * If the latter, the signature should be as follows:
  71. *
  72. * ```php
  73. * function ($model, $attribute)
  74. * ```
  75. *
  76. * The value of this property will be merged recursively with the `$options` parameter passed to [[field()]].
  77. *
  78. * @see fieldClass
  79. */
  80. public $fieldConfig = [];
  81. /**
  82. * @var bool whether to perform encoding on the error summary.
  83. */
  84. public $encodeErrorSummary = true;
  85. /**
  86. * @var string the default CSS class for the error summary container.
  87. * @see errorSummary()
  88. */
  89. public $errorSummaryCssClass = 'error-summary';
  90. /**
  91. * @var string the CSS class that is added to a field container when the associated attribute is required.
  92. */
  93. public $requiredCssClass = 'required';
  94. /**
  95. * @var string the CSS class that is added to a field container when the associated attribute has validation error.
  96. */
  97. public $errorCssClass = 'has-error';
  98. /**
  99. * @var string the CSS class that is added to a field container when the associated attribute is successfully validated.
  100. */
  101. public $successCssClass = 'has-success';
  102. /**
  103. * @var string the CSS class that is added to a field container when the associated attribute is being validated.
  104. */
  105. public $validatingCssClass = 'validating';
  106. /**
  107. * @var string where to render validation state class
  108. * Could be either "container" or "input".
  109. * Default is "container".
  110. * @since 2.0.14
  111. */
  112. public $validationStateOn = self::VALIDATION_STATE_ON_CONTAINER;
  113. /**
  114. * @var bool whether to enable client-side data validation.
  115. * If [[ActiveField::enableClientValidation]] is set, its value will take precedence for that input field.
  116. */
  117. public $enableClientValidation = true;
  118. /**
  119. * @var bool whether to enable AJAX-based data validation.
  120. * If [[ActiveField::enableAjaxValidation]] is set, its value will take precedence for that input field.
  121. */
  122. public $enableAjaxValidation = false;
  123. /**
  124. * @var bool whether to hook up `yii.activeForm` JavaScript plugin.
  125. * This property must be set `true` if you want to support client validation and/or AJAX validation, or if you
  126. * want to take advantage of the `yii.activeForm` plugin. When this is `false`, the form will not generate
  127. * any JavaScript.
  128. * @see registerClientScript
  129. */
  130. public $enableClientScript = true;
  131. /**
  132. * @var array|string the URL for performing AJAX-based validation. This property will be processed by
  133. * [[Url::to()]]. Please refer to [[Url::to()]] for more details on how to configure this property.
  134. * If this property is not set, it will take the value of the form's action attribute.
  135. */
  136. public $validationUrl;
  137. /**
  138. * @var bool whether to perform validation when the form is submitted.
  139. */
  140. public $validateOnSubmit = true;
  141. /**
  142. * @var bool whether to perform validation when the value of an input field is changed.
  143. * If [[ActiveField::validateOnChange]] is set, its value will take precedence for that input field.
  144. */
  145. public $validateOnChange = true;
  146. /**
  147. * @var bool whether to perform validation when an input field loses focus.
  148. * If [[ActiveField::$validateOnBlur]] is set, its value will take precedence for that input field.
  149. */
  150. public $validateOnBlur = true;
  151. /**
  152. * @var bool whether to perform validation while the user is typing in an input field.
  153. * If [[ActiveField::validateOnType]] is set, its value will take precedence for that input field.
  154. * @see validationDelay
  155. */
  156. public $validateOnType = false;
  157. /**
  158. * @var int number of milliseconds that the validation should be delayed when the user types in the field
  159. * and [[validateOnType]] is set `true`.
  160. * If [[ActiveField::validationDelay]] is set, its value will take precedence for that input field.
  161. */
  162. public $validationDelay = 500;
  163. /**
  164. * @var string the name of the GET parameter indicating the validation request is an AJAX request.
  165. */
  166. public $ajaxParam = 'ajax';
  167. /**
  168. * @var string the type of data that you're expecting back from the server.
  169. */
  170. public $ajaxDataType = 'json';
  171. /**
  172. * @var bool whether to scroll to the first error after validation.
  173. * @since 2.0.6
  174. */
  175. public $scrollToError = true;
  176. /**
  177. * @var int offset in pixels that should be added when scrolling to the first error.
  178. * @since 2.0.11
  179. */
  180. public $scrollToErrorOffset = 0;
  181. /**
  182. * @var array the client validation options for individual attributes. Each element of the array
  183. * represents the validation options for a particular attribute.
  184. * @internal
  185. */
  186. public $attributes = [];
  187. /**
  188. * @var ActiveField[] the ActiveField objects that are currently active
  189. */
  190. private $_fields = [];
  191. /**
  192. * Initializes the widget.
  193. * This renders the form open tag.
  194. */
  195. public function init()
  196. {
  197. parent::init();
  198. if (!isset($this->options['id'])) {
  199. $this->options['id'] = $this->getId();
  200. }
  201. ob_start();
  202. ob_implicit_flush(false);
  203. }
  204. /**
  205. * Runs the widget.
  206. * This registers the necessary JavaScript code and renders the form open and close tags.
  207. * @throws InvalidCallException if `beginField()` and `endField()` calls are not matching.
  208. */
  209. public function run()
  210. {
  211. if (!empty($this->_fields)) {
  212. throw new InvalidCallException('Each beginField() should have a matching endField() call.');
  213. }
  214. $content = ob_get_clean();
  215. $html = Html::beginForm($this->action, $this->method, $this->options);
  216. $html .= $content;
  217. if ($this->enableClientScript) {
  218. $this->registerClientScript();
  219. }
  220. $html .= Html::endForm();
  221. return $html;
  222. }
  223. /**
  224. * This registers the necessary JavaScript code.
  225. * @since 2.0.12
  226. */
  227. public function registerClientScript()
  228. {
  229. $id = $this->options['id'];
  230. $options = Json::htmlEncode($this->getClientOptions());
  231. $attributes = Json::htmlEncode($this->attributes);
  232. $view = $this->getView();
  233. ActiveFormAsset::register($view);
  234. $view->registerJs("jQuery('#$id').yiiActiveForm($attributes, $options);");
  235. }
  236. /**
  237. * Returns the options for the form JS widget.
  238. * @return array the options.
  239. */
  240. protected function getClientOptions()
  241. {
  242. $options = [
  243. 'encodeErrorSummary' => $this->encodeErrorSummary,
  244. 'errorSummary' => '.' . implode('.', preg_split('/\s+/', $this->errorSummaryCssClass, -1, PREG_SPLIT_NO_EMPTY)),
  245. 'validateOnSubmit' => $this->validateOnSubmit,
  246. 'errorCssClass' => $this->errorCssClass,
  247. 'successCssClass' => $this->successCssClass,
  248. 'validatingCssClass' => $this->validatingCssClass,
  249. 'ajaxParam' => $this->ajaxParam,
  250. 'ajaxDataType' => $this->ajaxDataType,
  251. 'scrollToError' => $this->scrollToError,
  252. 'scrollToErrorOffset' => $this->scrollToErrorOffset,
  253. 'validationStateOn' => $this->validationStateOn,
  254. ];
  255. if ($this->validationUrl !== null) {
  256. $options['validationUrl'] = Url::to($this->validationUrl);
  257. }
  258. // only get the options that are different from the default ones (set in yii.activeForm.js)
  259. return array_diff_assoc($options, [
  260. 'encodeErrorSummary' => true,
  261. 'errorSummary' => '.error-summary',
  262. 'validateOnSubmit' => true,
  263. 'errorCssClass' => 'has-error',
  264. 'successCssClass' => 'has-success',
  265. 'validatingCssClass' => 'validating',
  266. 'ajaxParam' => 'ajax',
  267. 'ajaxDataType' => 'json',
  268. 'scrollToError' => true,
  269. 'scrollToErrorOffset' => 0,
  270. 'validationStateOn' => self::VALIDATION_STATE_ON_CONTAINER,
  271. ]);
  272. }
  273. /**
  274. * Generates a summary of the validation errors.
  275. * If there is no validation error, an empty error summary markup will still be generated, but it will be hidden.
  276. * @param Model|Model[] $models the model(s) associated with this form.
  277. * @param array $options the tag options in terms of name-value pairs. The following options are specially handled:
  278. *
  279. * - `header`: string, the header HTML for the error summary. If not set, a default prompt string will be used.
  280. * - `footer`: string, the footer HTML for the error summary.
  281. *
  282. * The rest of the options will be rendered as the attributes of the container tag. The values will
  283. * be HTML-encoded using [[\yii\helpers\Html::encode()]]. If a value is `null`, the corresponding attribute will not be rendered.
  284. * @return string the generated error summary.
  285. * @see errorSummaryCssClass
  286. */
  287. public function errorSummary($models, $options = [])
  288. {
  289. Html::addCssClass($options, $this->errorSummaryCssClass);
  290. $options['encode'] = $this->encodeErrorSummary;
  291. return Html::errorSummary($models, $options);
  292. }
  293. /**
  294. * Generates a form field.
  295. * A form field is associated with a model and an attribute. It contains a label, an input and an error message
  296. * and use them to interact with end users to collect their inputs for the attribute.
  297. * @param Model $model the data model.
  298. * @param string $attribute the attribute name or expression. See [[Html::getAttributeName()]] for the format
  299. * about attribute expression.
  300. * @param array $options the additional configurations for the field object. These are properties of [[ActiveField]]
  301. * or a subclass, depending on the value of [[fieldClass]].
  302. * @return ActiveField the created ActiveField object.
  303. * @see fieldConfig
  304. */
  305. public function field($model, $attribute, $options = [])
  306. {
  307. $config = $this->fieldConfig;
  308. if ($config instanceof \Closure) {
  309. $config = call_user_func($config, $model, $attribute);
  310. }
  311. if (!isset($config['class'])) {
  312. $config['class'] = $this->fieldClass;
  313. }
  314. return Yii::createObject(ArrayHelper::merge($config, $options, [
  315. 'model' => $model,
  316. 'attribute' => $attribute,
  317. 'form' => $this,
  318. ]));
  319. }
  320. /**
  321. * Begins a form field.
  322. * This method will create a new form field and returns its opening tag.
  323. * You should call [[endField()]] afterwards.
  324. * @param Model $model the data model.
  325. * @param string $attribute the attribute name or expression. See [[Html::getAttributeName()]] for the format
  326. * about attribute expression.
  327. * @param array $options the additional configurations for the field object.
  328. * @return string the opening tag.
  329. * @see endField()
  330. * @see field()
  331. */
  332. public function beginField($model, $attribute, $options = [])
  333. {
  334. $field = $this->field($model, $attribute, $options);
  335. $this->_fields[] = $field;
  336. return $field->begin();
  337. }
  338. /**
  339. * Ends a form field.
  340. * This method will return the closing tag of an active form field started by [[beginField()]].
  341. * @return string the closing tag of the form field.
  342. * @throws InvalidCallException if this method is called without a prior [[beginField()]] call.
  343. */
  344. public function endField()
  345. {
  346. $field = array_pop($this->_fields);
  347. if ($field instanceof ActiveField) {
  348. return $field->end();
  349. }
  350. throw new InvalidCallException('Mismatching endField() call.');
  351. }
  352. /**
  353. * Validates one or several models and returns an error message array indexed by the attribute IDs.
  354. * This is a helper method that simplifies the way of writing AJAX validation code.
  355. *
  356. * For example, you may use the following code in a controller action to respond
  357. * to an AJAX validation request:
  358. *
  359. * ```php
  360. * $model = new Post;
  361. * $model->load(Yii::$app->request->post());
  362. * if (Yii::$app->request->isAjax) {
  363. * Yii::$app->response->format = Response::FORMAT_JSON;
  364. * return ActiveForm::validate($model);
  365. * }
  366. * // ... respond to non-AJAX request ...
  367. * ```
  368. *
  369. * To validate multiple models, simply pass each model as a parameter to this method, like
  370. * the following:
  371. *
  372. * ```php
  373. * ActiveForm::validate($model1, $model2, ...);
  374. * ```
  375. *
  376. * @param Model $model the model to be validated.
  377. * @param mixed $attributes list of attributes that should be validated.
  378. * If this parameter is empty, it means any attribute listed in the applicable
  379. * validation rules should be validated.
  380. *
  381. * When this method is used to validate multiple models, this parameter will be interpreted
  382. * as a model.
  383. *
  384. * @return array the error message array indexed by the attribute IDs.
  385. */
  386. public static function validate($model, $attributes = null)
  387. {
  388. $result = [];
  389. if ($attributes instanceof Model) {
  390. // validating multiple models
  391. $models = func_get_args();
  392. $attributes = null;
  393. } else {
  394. $models = [$model];
  395. }
  396. /* @var $model Model */
  397. foreach ($models as $model) {
  398. $model->validate($attributes);
  399. foreach ($model->getErrors() as $attribute => $errors) {
  400. $result[Html::getInputId($model, $attribute)] = $errors;
  401. }
  402. }
  403. return $result;
  404. }
  405. /**
  406. * Validates an array of model instances and returns an error message array indexed by the attribute IDs.
  407. * This is a helper method that simplifies the way of writing AJAX validation code for tabular input.
  408. *
  409. * For example, you may use the following code in a controller action to respond
  410. * to an AJAX validation request:
  411. *
  412. * ```php
  413. * // ... load $models ...
  414. * if (Yii::$app->request->isAjax) {
  415. * Yii::$app->response->format = Response::FORMAT_JSON;
  416. * return ActiveForm::validateMultiple($models);
  417. * }
  418. * // ... respond to non-AJAX request ...
  419. * ```
  420. *
  421. * @param array $models an array of models to be validated.
  422. * @param mixed $attributes list of attributes that should be validated.
  423. * If this parameter is empty, it means any attribute listed in the applicable
  424. * validation rules should be validated.
  425. * @return array the error message array indexed by the attribute IDs.
  426. */
  427. public static function validateMultiple($models, $attributes = null)
  428. {
  429. $result = [];
  430. /* @var $model Model */
  431. foreach ($models as $i => $model) {
  432. $model->validate($attributes);
  433. foreach ($model->getErrors() as $attribute => $errors) {
  434. $result[Html::getInputId($model, "[$i]" . $attribute)] = $errors;
  435. }
  436. }
  437. return $result;
  438. }
  439. }