You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

416 satır
15KB

  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\bootstrap;
  8. use yii\helpers\ArrayHelper;
  9. /**
  10. * A Bootstrap 3 enhanced version of [[\yii\widgets\ActiveField]].
  11. *
  12. * This class adds some useful features to [[\yii\widgets\ActiveField|ActiveField]] to render all
  13. * sorts of Bootstrap 3 form fields in different form layouts:
  14. *
  15. * - [[inputTemplate]] is an optional template to render complex inputs, for example input groups
  16. * - [[horizontalCssClasses]] defines the CSS grid classes to add to label, wrapper, error and hint
  17. * in horizontal forms
  18. * - [[inline]]/[[inline()]] is used to render inline [[checkboxList()]] and [[radioList()]]
  19. * - [[enableError]] can be set to `false` to disable to the error
  20. * - [[enableLabel]] can be set to `false` to disable to the label
  21. * - [[label()]] can be used with a `boolean` argument to enable/disable the label
  22. *
  23. * There are also some new placeholders that you can use in the [[template]] configuration:
  24. *
  25. * - `{beginLabel}`: the opening label tag
  26. * - `{labelTitle}`: the label title for use with `{beginLabel}`/`{endLabel}`
  27. * - `{endLabel}`: the closing label tag
  28. * - `{beginWrapper}`: the opening wrapper tag
  29. * - `{endWrapper}`: the closing wrapper tag
  30. *
  31. * The wrapper tag is only used for some layouts and form elements.
  32. *
  33. * Note that some elements use slightly different defaults for [[template]] and other options.
  34. * You may want to override those predefined templates for checkboxes, radio buttons, checkboxLists
  35. * and radioLists in the [[\yii\widgets\ActiveForm::fieldConfig|fieldConfig]] of the
  36. * [[\yii\widgets\ActiveForm]]:
  37. *
  38. * - [[checkboxTemplate]] the template for checkboxes in default layout
  39. * - [[radioTemplate]] the template for radio buttons in default layout
  40. * - [[horizontalCheckboxTemplate]] the template for checkboxes in horizontal layout
  41. * - [[horizontalRadioTemplate]] the template for radio buttons in horizontal layout
  42. * - [[inlineCheckboxListTemplate]] the template for inline checkboxLists
  43. * - [[inlineRadioListTemplate]] the template for inline radioLists
  44. *
  45. * Example:
  46. *
  47. * ```php
  48. * use yii\bootstrap\ActiveForm;
  49. *
  50. * $form = ActiveForm::begin(['layout' => 'horizontal']);
  51. *
  52. * // Form field without label
  53. * echo $form->field($model, 'demo', [
  54. * 'inputOptions' => [
  55. * 'placeholder' => $model->getAttributeLabel('demo'),
  56. * ],
  57. * ])->label(false);
  58. *
  59. * // Inline radio list
  60. * echo $form->field($model, 'demo')->inline()->radioList($items);
  61. *
  62. * // Control sizing in horizontal mode
  63. * echo $form->field($model, 'demo', [
  64. * 'horizontalCssClasses' => [
  65. * 'wrapper' => 'col-sm-2',
  66. * ]
  67. * ]);
  68. *
  69. * // With 'default' layout you would use 'template' to size a specific field:
  70. * echo $form->field($model, 'demo', [
  71. * 'template' => '{label} <div class="row"><div class="col-sm-4">{input}{error}{hint}</div></div>'
  72. * ]);
  73. *
  74. * // Input group
  75. * echo $form->field($model, 'demo', [
  76. * 'inputTemplate' => '<div class="input-group"><span class="input-group-addon">@</span>{input}</div>',
  77. * ]);
  78. *
  79. * ActiveForm::end();
  80. * ```
  81. *
  82. * @see \yii\bootstrap\ActiveForm
  83. * @see http://getbootstrap.com/css/#forms
  84. *
  85. * @author Michael Härtl <haertl.mike@gmail.com>
  86. * @since 2.0
  87. */
  88. class ActiveField extends \yii\widgets\ActiveField
  89. {
  90. /**
  91. * @var boolean whether to render [[checkboxList()]] and [[radioList()]] inline.
  92. */
  93. public $inline = false;
  94. /**
  95. * @var string|null optional template to render the `{input}` placeholder content
  96. */
  97. public $inputTemplate;
  98. /**
  99. * @var array options for the wrapper tag, used in the `{beginWrapper}` placeholder
  100. */
  101. public $wrapperOptions = [];
  102. /**
  103. * @var null|array CSS grid classes for horizontal layout. This must be an array with these keys:
  104. * - 'offset' the offset grid class to append to the wrapper if no label is rendered
  105. * - 'label' the label grid class
  106. * - 'wrapper' the wrapper grid class
  107. * - 'error' the error grid class
  108. * - 'hint' the hint grid class
  109. */
  110. public $horizontalCssClasses;
  111. /**
  112. * @var string the template for checkboxes in default layout
  113. */
  114. public $checkboxTemplate = "<div class=\"checkbox\">\n{beginLabel}\n{input}\n{labelTitle}\n{endLabel}\n{error}\n{hint}\n</div>";
  115. /**
  116. * @var string the template for radios in default layout
  117. */
  118. public $radioTemplate = "<div class=\"radio\">\n{beginLabel}\n{input}\n{labelTitle}\n{endLabel}\n{error}\n{hint}\n</div>";
  119. /**
  120. * @var string the template for checkboxes in horizontal layout
  121. */
  122. public $horizontalCheckboxTemplate = "{beginWrapper}\n<div class=\"checkbox\">\n{beginLabel}\n{input}\n{labelTitle}\n{endLabel}\n</div>\n{error}\n{endWrapper}\n{hint}";
  123. /**
  124. * @var string the template for radio buttons in horizontal layout
  125. */
  126. public $horizontalRadioTemplate = "{beginWrapper}\n<div class=\"radio\">\n{beginLabel}\n{input}\n{labelTitle}\n{endLabel}\n</div>\n{error}\n{endWrapper}\n{hint}";
  127. /**
  128. * @var string the template for inline checkboxLists
  129. */
  130. public $inlineCheckboxListTemplate = "{label}\n{beginWrapper}\n{input}\n{error}\n{endWrapper}\n{hint}";
  131. /**
  132. * @var string the template for inline radioLists
  133. */
  134. public $inlineRadioListTemplate = "{label}\n{beginWrapper}\n{input}\n{error}\n{endWrapper}\n{hint}";
  135. /**
  136. * @var boolean whether to render the error. Default is `true` except for layout `inline`.
  137. */
  138. public $enableError = true;
  139. /**
  140. * @var boolean whether to render the label. Default is `true`.
  141. */
  142. public $enableLabel = true;
  143. /**
  144. * @inheritdoc
  145. */
  146. public function __construct($config = [])
  147. {
  148. $layoutConfig = $this->createLayoutConfig($config);
  149. $config = ArrayHelper::merge($layoutConfig, $config);
  150. parent::__construct($config);
  151. }
  152. /**
  153. * @inheritdoc
  154. */
  155. public function render($content = null)
  156. {
  157. if ($content === null) {
  158. if (!isset($this->parts['{beginWrapper}'])) {
  159. $options = $this->wrapperOptions;
  160. $tag = ArrayHelper::remove($options, 'tag', 'div');
  161. $this->parts['{beginWrapper}'] = Html::beginTag($tag, $options);
  162. $this->parts['{endWrapper}'] = Html::endTag($tag);
  163. }
  164. if ($this->enableLabel === false) {
  165. $this->parts['{label}'] = '';
  166. $this->parts['{beginLabel}'] = '';
  167. $this->parts['{labelTitle}'] = '';
  168. $this->parts['{endLabel}'] = '';
  169. } elseif (!isset($this->parts['{beginLabel}'])) {
  170. $this->renderLabelParts();
  171. }
  172. if ($this->enableError === false) {
  173. $this->parts['{error}'] = '';
  174. }
  175. if ($this->inputTemplate) {
  176. $input = isset($this->parts['{input}']) ?
  177. $this->parts['{input}'] : Html::activeTextInput($this->model, $this->attribute, $this->inputOptions);
  178. $this->parts['{input}'] = strtr($this->inputTemplate, ['{input}' => $input]);
  179. }
  180. }
  181. return parent::render($content);
  182. }
  183. /**
  184. * @inheritdoc
  185. */
  186. public function checkbox($options = [], $enclosedByLabel = true)
  187. {
  188. if ($enclosedByLabel) {
  189. if (!isset($options['template'])) {
  190. $this->template = $this->form->layout === 'horizontal' ?
  191. $this->horizontalCheckboxTemplate : $this->checkboxTemplate;
  192. } else {
  193. $this->template = $options['template'];
  194. unset($options['template']);
  195. }
  196. if (isset($options['label'])) {
  197. $this->parts['{labelTitle}'] = $options['label'];
  198. }
  199. if ($this->form->layout === 'horizontal') {
  200. Html::addCssClass($this->wrapperOptions, $this->horizontalCssClasses['offset']);
  201. }
  202. $this->labelOptions['class'] = null;
  203. }
  204. return parent::checkbox($options, false);
  205. }
  206. /**
  207. * @inheritdoc
  208. */
  209. public function radio($options = [], $enclosedByLabel = true)
  210. {
  211. if ($enclosedByLabel) {
  212. if (!isset($options['template'])) {
  213. $this->template = $this->form->layout === 'horizontal' ?
  214. $this->horizontalRadioTemplate : $this->radioTemplate;
  215. } else {
  216. $this->template = $options['template'];
  217. unset($options['template']);
  218. }
  219. if (isset($options['label'])) {
  220. $this->parts['{labelTitle}'] = $options['label'];
  221. }
  222. if ($this->form->layout === 'horizontal') {
  223. Html::addCssClass($this->wrapperOptions, $this->horizontalCssClasses['offset']);
  224. }
  225. $this->labelOptions['class'] = null;
  226. }
  227. return parent::radio($options, false);
  228. }
  229. /**
  230. * @inheritdoc
  231. */
  232. public function checkboxList($items, $options = [])
  233. {
  234. if ($this->inline) {
  235. if (!isset($options['template'])) {
  236. $this->template = $this->inlineCheckboxListTemplate;
  237. } else {
  238. $this->template = $options['template'];
  239. unset($options['template']);
  240. }
  241. if (!isset($options['itemOptions'])) {
  242. $options['itemOptions'] = [
  243. 'labelOptions' => ['class' => 'checkbox-inline'],
  244. ];
  245. }
  246. } elseif (!isset($options['item'])) {
  247. $itemOptions = isset($options['itemOptions']) ? $options['itemOptions'] : [];
  248. $options['item'] = function ($index, $label, $name, $checked, $value) use ($itemOptions) {
  249. $options = array_merge(['label' => $label, 'value' => $value], $itemOptions);
  250. return '<div class="checkbox">' . Html::checkbox($name, $checked, $options) . '</div>';
  251. };
  252. }
  253. parent::checkboxList($items, $options);
  254. return $this;
  255. }
  256. /**
  257. * @inheritdoc
  258. */
  259. public function radioList($items, $options = [])
  260. {
  261. if ($this->inline) {
  262. if (!isset($options['template'])) {
  263. $this->template = $this->inlineRadioListTemplate;
  264. } else {
  265. $this->template = $options['template'];
  266. unset($options['template']);
  267. }
  268. if (!isset($options['itemOptions'])) {
  269. $options['itemOptions'] = [
  270. 'labelOptions' => ['class' => 'radio-inline'],
  271. ];
  272. }
  273. } elseif (!isset($options['item'])) {
  274. $itemOptions = isset($options['itemOptions']) ? $options['itemOptions'] : [];
  275. $options['item'] = function ($index, $label, $name, $checked, $value) use ($itemOptions) {
  276. $options = array_merge(['label' => $label, 'value' => $value], $itemOptions);
  277. return '<div class="radio">' . Html::radio($name, $checked, $options) . '</div>';
  278. };
  279. }
  280. parent::radioList($items, $options);
  281. return $this;
  282. }
  283. /**
  284. * Renders Bootstrap static form control.
  285. * @param array $options the tag options in terms of name-value pairs. These will be rendered as
  286. * the attributes of the resulting tag. There are also a special options:
  287. *
  288. * - encode: boolean, whether value should be HTML-encoded or not.
  289. *
  290. * @return $this the field object itself
  291. * @since 2.0.5
  292. * @see http://getbootstrap.com/css/#forms-controls-static
  293. */
  294. public function staticControl($options = [])
  295. {
  296. $this->adjustLabelFor($options);
  297. $this->parts['{input}'] = Html::activeStaticControl($this->model, $this->attribute, $options);
  298. return $this;
  299. }
  300. /**
  301. * @inheritdoc
  302. */
  303. public function label($label = null, $options = [])
  304. {
  305. if (is_bool($label)) {
  306. $this->enableLabel = $label;
  307. if ($label === false && $this->form->layout === 'horizontal') {
  308. Html::addCssClass($this->wrapperOptions, $this->horizontalCssClasses['offset']);
  309. }
  310. } else {
  311. $this->enableLabel = true;
  312. $this->renderLabelParts($label, $options);
  313. parent::label($label, $options);
  314. }
  315. return $this;
  316. }
  317. /**
  318. * @param boolean $value whether to render a inline list
  319. * @return $this the field object itself
  320. * Make sure you call this method before [[checkboxList()]] or [[radioList()]] to have any effect.
  321. */
  322. public function inline($value = true)
  323. {
  324. $this->inline = (bool) $value;
  325. return $this;
  326. }
  327. /**
  328. * @param array $instanceConfig the configuration passed to this instance's constructor
  329. * @return array the layout specific default configuration for this instance
  330. */
  331. protected function createLayoutConfig($instanceConfig)
  332. {
  333. $config = [
  334. 'hintOptions' => [
  335. 'tag' => 'p',
  336. 'class' => 'help-block',
  337. ],
  338. 'errorOptions' => [
  339. 'tag' => 'p',
  340. 'class' => 'help-block help-block-error',
  341. ],
  342. 'inputOptions' => [
  343. 'class' => 'form-control',
  344. ],
  345. ];
  346. $layout = $instanceConfig['form']->layout;
  347. if ($layout === 'horizontal') {
  348. $config['template'] = "{label}\n{beginWrapper}\n{input}\n{error}\n{endWrapper}\n{hint}";
  349. $cssClasses = [
  350. 'offset' => 'col-sm-offset-3',
  351. 'label' => 'col-sm-3',
  352. 'wrapper' => 'col-sm-6',
  353. 'error' => '',
  354. 'hint' => 'col-sm-3',
  355. ];
  356. if (isset($instanceConfig['horizontalCssClasses'])) {
  357. $cssClasses = ArrayHelper::merge($cssClasses, $instanceConfig['horizontalCssClasses']);
  358. }
  359. $config['horizontalCssClasses'] = $cssClasses;
  360. $config['wrapperOptions'] = ['class' => $cssClasses['wrapper']];
  361. $config['labelOptions'] = ['class' => 'control-label ' . $cssClasses['label']];
  362. $config['errorOptions'] = ['class' => 'help-block help-block-error ' . $cssClasses['error']];
  363. $config['hintOptions'] = ['class' => 'help-block ' . $cssClasses['hint']];
  364. } elseif ($layout === 'inline') {
  365. $config['labelOptions'] = ['class' => 'sr-only'];
  366. $config['enableError'] = false;
  367. }
  368. return $config;
  369. }
  370. /**
  371. * @param string|null $label the label or null to use model label
  372. * @param array $options the tag options
  373. */
  374. protected function renderLabelParts($label = null, $options = [])
  375. {
  376. $options = array_merge($this->labelOptions, $options);
  377. if ($label === null) {
  378. if (isset($options['label'])) {
  379. $label = $options['label'];
  380. unset($options['label']);
  381. } else {
  382. $attribute = Html::getAttributeName($this->attribute);
  383. $label = Html::encode($this->model->getAttributeLabel($attribute));
  384. }
  385. }
  386. if (!isset($options['for'])) {
  387. $options['for'] = Html::getInputId($this->model, $this->attribute);
  388. }
  389. $this->parts['{beginLabel}'] = Html::beginTag('label', $options);
  390. $this->parts['{endLabel}'] = Html::endTag('label');
  391. if (!isset($this->parts['{labelTitle}'])) {
  392. $this->parts['{labelTitle}'] = $label;
  393. }
  394. }
  395. }