ActiveForm.php 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357
  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\Widget;
  10. use yii\base\Model;
  11. use yii\helpers\Html;
  12. use yii\helpers\Json;
  13. use yii\web\JsExpression;
  14. /**
  15. * ActiveForm ...
  16. *
  17. * @author Qiang Xue <[email protected]>
  18. * @since 2.0
  19. */
  20. class ActiveForm extends Widget
  21. {
  22. /**
  23. * @param array|string $action the form action URL. This parameter will be processed by [[\yii\helpers\Html::url()]].
  24. */
  25. public $action = '';
  26. /**
  27. * @var string the form submission method. This should be either 'post' or 'get'.
  28. * Defaults to 'post'.
  29. */
  30. public $method = 'post';
  31. /**
  32. * @var array the HTML attributes (name-value pairs) for the form tag.
  33. * The values will be HTML-encoded using [[Html::encode()]].
  34. * If a value is null, the corresponding attribute will not be rendered.
  35. */
  36. public $options = [];
  37. /**
  38. * @var array the default configuration used by [[field()]] when creating a new field object.
  39. */
  40. public $fieldConfig;
  41. /**
  42. * @var string the default CSS class for the error summary container.
  43. * @see errorSummary()
  44. */
  45. public $errorSummaryCssClass = 'error-summary';
  46. /**
  47. * @var string the CSS class that is added to a field container when the associated attribute is required.
  48. */
  49. public $requiredCssClass = 'required';
  50. /**
  51. * @var string the CSS class that is added to a field container when the associated attribute has validation error.
  52. */
  53. public $errorCssClass = 'has-error';
  54. /**
  55. * @var string the CSS class that is added to a field container when the associated attribute is successfully validated.
  56. */
  57. public $successCssClass = 'has-success';
  58. /**
  59. * @var string the CSS class that is added to a field container when the associated attribute is being validated.
  60. */
  61. public $validatingCssClass = 'validating';
  62. /**
  63. * @var boolean whether to enable client-side data validation.
  64. * If [[ActiveField::enableClientValidation]] is set, its value will take precedence for that input field.
  65. */
  66. public $enableClientValidation = true;
  67. /**
  68. * @var boolean whether to enable AJAX-based data validation.
  69. * If [[ActiveField::enableAjaxValidation]] is set, its value will take precedence for that input field.
  70. */
  71. public $enableAjaxValidation = false;
  72. /**
  73. * @var array|string the URL for performing AJAX-based validation. This property will be processed by
  74. * [[Html::url()]]. Please refer to [[Html::url()]] for more details on how to configure this property.
  75. * If this property is not set, it will take the value of the form's action attribute.
  76. */
  77. public $validationUrl;
  78. /**
  79. * @var boolean whether to perform validation when the form is submitted.
  80. */
  81. public $validateOnSubmit = true;
  82. /**
  83. * @var boolean whether to perform validation when an input field loses focus and its value is found changed.
  84. * If [[ActiveField::validateOnChange]] is set, its value will take precedence for that input field.
  85. */
  86. public $validateOnChange = true;
  87. /**
  88. * @var boolean whether to perform validation while the user is typing in an input field.
  89. * If [[ActiveField::validateOnType]] is set, its value will take precedence for that input field.
  90. * @see validationDelay
  91. */
  92. public $validateOnType = false;
  93. /**
  94. * @var integer number of milliseconds that the validation should be delayed when an input field
  95. * is changed or the user types in the field.
  96. * If [[ActiveField::validationDelay]] is set, its value will take precedence for that input field.
  97. */
  98. public $validationDelay = 200;
  99. /**
  100. * @var string the name of the GET parameter indicating the validation request is an AJAX request.
  101. */
  102. public $ajaxVar = 'ajax';
  103. /**
  104. * @var string|JsExpression a JS callback that will be called when the form is being submitted.
  105. * The signature of the callback should be:
  106. *
  107. * ~~~
  108. * function ($form) {
  109. * ...return false to cancel submission...
  110. * }
  111. * ~~~
  112. */
  113. public $beforeSubmit;
  114. /**
  115. * @var string|JsExpression a JS callback that is called before validating an attribute.
  116. * The signature of the callback should be:
  117. *
  118. * ~~~
  119. * function ($form, attribute, messages) {
  120. * ...return false to cancel the validation...
  121. * }
  122. * ~~~
  123. */
  124. public $beforeValidate;
  125. /**
  126. * @var string|JsExpression a JS callback that is called after validating an attribute.
  127. * The signature of the callback should be:
  128. *
  129. * ~~~
  130. * function ($form, attribute, messages) {
  131. * }
  132. * ~~~
  133. */
  134. public $afterValidate;
  135. /**
  136. * @var array the client validation options for individual attributes. Each element of the array
  137. * represents the validation options for a particular attribute.
  138. * @internal
  139. */
  140. public $attributes = [];
  141. /**
  142. * Initializes the widget.
  143. * This renders the form open tag.
  144. */
  145. public function init()
  146. {
  147. if (!isset($this->options['id'])) {
  148. $this->options['id'] = $this->getId();
  149. }
  150. if (!isset($this->fieldConfig['class'])) {
  151. $this->fieldConfig['class'] = ActiveField::className();
  152. }
  153. echo Html::beginForm($this->action, $this->method, $this->options);
  154. }
  155. /**
  156. * Runs the widget.
  157. * This registers the necessary javascript code and renders the form close tag.
  158. */
  159. public function run()
  160. {
  161. if (!empty($this->attributes)) {
  162. $id = $this->options['id'];
  163. $options = Json::encode($this->getClientOptions());
  164. $attributes = Json::encode($this->attributes);
  165. $view = $this->getView();
  166. ActiveFormAsset::register($view);
  167. $view->registerJs("jQuery('#$id').yiiActiveForm($attributes, $options);");
  168. }
  169. echo Html::endForm();
  170. }
  171. /**
  172. * Returns the options for the form JS widget.
  173. * @return array the options
  174. */
  175. protected function getClientOptions()
  176. {
  177. $options = [
  178. 'errorSummary' => '.' . $this->errorSummaryCssClass,
  179. 'validateOnSubmit' => $this->validateOnSubmit,
  180. 'errorCssClass' => $this->errorCssClass,
  181. 'successCssClass' => $this->successCssClass,
  182. 'validatingCssClass' => $this->validatingCssClass,
  183. 'ajaxVar' => $this->ajaxVar,
  184. ];
  185. if ($this->validationUrl !== null) {
  186. $options['validationUrl'] = Html::url($this->validationUrl);
  187. }
  188. foreach (['beforeSubmit', 'beforeValidate', 'afterValidate'] as $name) {
  189. if (($value = $this->$name) !== null) {
  190. $options[$name] = $value instanceof JsExpression ? $value : new JsExpression($value);
  191. }
  192. }
  193. return $options;
  194. }
  195. /**
  196. * Generates a summary of the validation errors.
  197. * If there is no validation error, an empty error summary markup will still be generated, but it will be hidden.
  198. * @param Model|Model[] $models the model(s) associated with this form
  199. * @param array $options the tag options in terms of name-value pairs. The following options are specially handled:
  200. *
  201. * - header: string, the header HTML for the error summary. If not set, a default prompt string will be used.
  202. * - footer: string, the footer HTML for the error summary.
  203. *
  204. * The rest of the options will be rendered as the attributes of the container tag. The values will
  205. * be HTML-encoded using [[encode()]]. If a value is null, the corresponding attribute will not be rendered.
  206. * @return string the generated error summary
  207. */
  208. public function errorSummary($models, $options = [])
  209. {
  210. if (!is_array($models)) {
  211. $models = [$models];
  212. }
  213. $lines = [];
  214. foreach ($models as $model) {
  215. /** @var Model $model */
  216. foreach ($model->getFirstErrors() as $error) {
  217. $lines[] = Html::encode($error);
  218. }
  219. }
  220. $header = isset($options['header']) ? $options['header'] : '<p>' . Yii::t('yii', 'Please fix the following errors:') . '</p>';
  221. $footer = isset($options['footer']) ? $options['footer'] : '';
  222. unset($options['header'], $options['footer']);
  223. if (!isset($options['class'])) {
  224. $options['class'] = $this->errorSummaryCssClass;
  225. } else {
  226. $options['class'] .= ' ' . $this->errorSummaryCssClass;
  227. }
  228. if (!empty($lines)) {
  229. $content = "<ul><li>" . implode("</li>\n<li>", $lines) . "</li><ul>";
  230. return Html::tag('div', $header . $content . $footer, $options);
  231. } else {
  232. $content = "<ul></ul>";
  233. $options['style'] = isset($options['style']) ? rtrim($options['style'], ';') . '; display:none' : 'display:none';
  234. return Html::tag('div', $header . $content . $footer, $options);
  235. }
  236. }
  237. /**
  238. * Generates a form field.
  239. * A form field is associated with a model and an attribute. It contains a label, an input and an error message
  240. * and use them to interact with end users to collect their inputs for the attribute.
  241. * @param Model $model the data model
  242. * @param string $attribute the attribute name or expression. See [[Html::getAttributeName()]] for the format
  243. * about attribute expression.
  244. * @param array $options the additional configurations for the field object
  245. * @return ActiveField the created ActiveField object
  246. * @see fieldConfig
  247. */
  248. public function field($model, $attribute, $options = [])
  249. {
  250. return Yii::createObject(array_merge($this->fieldConfig, $options, [
  251. 'model' => $model,
  252. 'attribute' => $attribute,
  253. 'form' => $this,
  254. ]));
  255. }
  256. /**
  257. * Validates one or several models and returns an error message array indexed by the attribute IDs.
  258. * This is a helper method that simplifies the way of writing AJAX validation code.
  259. *
  260. * For example, you may use the following code in a controller action to respond
  261. * to an AJAX validation request:
  262. *
  263. * ~~~
  264. * $model = new Post;
  265. * $model->load($_POST);
  266. * if (Yii::$app->request->isAjax) {
  267. * Yii::$app->response->format = Response::FORMAT_JSON;
  268. * return ActiveForm::validate($model);
  269. * }
  270. * // ... respond to non-AJAX request ...
  271. * ~~~
  272. *
  273. * To validate multiple models, simply pass each model as a parameter to this method, like
  274. * the following:
  275. *
  276. * ~~~
  277. * ActiveForm::validate($model1, $model2, ...);
  278. * ~~~
  279. *
  280. * @param Model $model the model to be validated
  281. * @param mixed $attributes list of attributes that should be validated.
  282. * If this parameter is empty, it means any attribute listed in the applicable
  283. * validation rules should be validated.
  284. *
  285. * When this method is used to validate multiple models, this parameter will be interpreted
  286. * as a model.
  287. *
  288. * @return array the error message array indexed by the attribute IDs.
  289. */
  290. public static function validate($model, $attributes = null)
  291. {
  292. $result = [];
  293. if ($attributes instanceof Model) {
  294. // validating multiple models
  295. $models = func_get_args();
  296. $attributes = null;
  297. } else {
  298. $models = [$model];
  299. }
  300. /** @var Model $model */
  301. foreach ($models as $model) {
  302. $model->validate($attributes);
  303. foreach ($model->getErrors() as $attribute => $errors) {
  304. $result[Html::getInputId($model, $attribute)] = $errors;
  305. }
  306. }
  307. return $result;
  308. }
  309. /**
  310. * Validates an array of model instances and returns an error message array indexed by the attribute IDs.
  311. * This is a helper method that simplifies the way of writing AJAX validation code for tabular input.
  312. *
  313. * For example, you may use the following code in a controller action to respond
  314. * to an AJAX validation request:
  315. *
  316. * ~~~
  317. * // ... load $models ...
  318. * if (Yii::$app->request->isAjax) {
  319. * Yii::$app->response->format = Response::FORMAT_JSON;
  320. * return ActiveForm::validateMultiple($models);
  321. * }
  322. * // ... respond to non-AJAX request ...
  323. * ~~~
  324. *
  325. * @param array $models an array of models to be validated.
  326. * @param mixed $attributes list of attributes that should be validated.
  327. * If this parameter is empty, it means any attribute listed in the applicable
  328. * validation rules should be validated.
  329. * @return array the error message array indexed by the attribute IDs.
  330. */
  331. public static function validateMultiple($models, $attributes = null)
  332. {
  333. $result = [];
  334. /** @var Model $model */
  335. foreach ($models as $i => $model) {
  336. $model->validate($attributes);
  337. foreach ($model->getErrors() as $attribute => $errors) {
  338. $result[Html::getInputId($model, "[$i]" . $attribute)] = $errors;
  339. }
  340. }
  341. return $result;
  342. }
  343. }