ActiveForm.php 16 KB

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