ActiveForm.php 16 KB

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