83 rindas
2.3KB

  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\base\InvalidConfigException;
  12. use yii\helpers\Html;
  13. /**
  14. * InputWidget is the base class for widgets that collect user inputs.
  15. *
  16. * An input widget can be associated with a data model and an attribute,
  17. * or a name and a value. If the former, the name and the value will
  18. * be generated automatically.
  19. *
  20. * Classes extending from this widget can be used in an [[\yii\widgets\ActiveForm|ActiveForm]]
  21. * using the [[\yii\widgets\ActiveField::widget()|widget()]] method, for example like this:
  22. *
  23. * ```php
  24. * <?= $form->field($model, 'from_date')->widget('WidgetClassName', [
  25. * // configure additional widget properties here
  26. * ]) ?>
  27. * ```
  28. *
  29. * @author Qiang Xue <qiang.xue@gmail.com>
  30. * @since 2.0
  31. */
  32. class InputWidget extends Widget
  33. {
  34. /**
  35. * @var Model the data model that this widget is associated with.
  36. */
  37. public $model;
  38. /**
  39. * @var string the model attribute that this widget is associated with.
  40. */
  41. public $attribute;
  42. /**
  43. * @var string the input name. This must be set if [[model]] and [[attribute]] are not set.
  44. */
  45. public $name;
  46. /**
  47. * @var string the input value.
  48. */
  49. public $value;
  50. /**
  51. * @var array the HTML attributes for the input tag.
  52. * @see \yii\helpers\Html::renderTagAttributes() for details on how attributes are being rendered.
  53. */
  54. public $options = [];
  55. /**
  56. * Initializes the widget.
  57. * If you override this method, make sure you call the parent implementation first.
  58. */
  59. public function init()
  60. {
  61. if ($this->name === null && !$this->hasModel()) {
  62. throw new InvalidConfigException("Either 'name', or 'model' and 'attribute' properties must be specified.");
  63. }
  64. if (!isset($this->options['id'])) {
  65. $this->options['id'] = $this->hasModel() ? Html::getInputId($this->model, $this->attribute) : $this->getId();
  66. }
  67. parent::init();
  68. }
  69. /**
  70. * @return boolean whether this widget is associated with a data model.
  71. */
  72. protected function hasModel()
  73. {
  74. return $this->model instanceof Model && $this->attribute !== null;
  75. }
  76. }