InputWidget.php 1.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172
  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. * @author Qiang Xue <[email protected]>
  21. * @since 2.0
  22. */
  23. class InputWidget extends Widget
  24. {
  25. /**
  26. * @var Model the data model that this widget is associated with.
  27. */
  28. public $model;
  29. /**
  30. * @var string the model attribute that this widget is associated with.
  31. */
  32. public $attribute;
  33. /**
  34. * @var string the input name. This must be set if [[model]] and [[attribute]] are not set.
  35. */
  36. public $name;
  37. /**
  38. * @var string the input value.
  39. */
  40. public $value;
  41. /**
  42. * @var array the HTML attributes for the input tag.
  43. */
  44. public $options = [];
  45. /**
  46. * Initializes the widget.
  47. * If you override this method, make sure you call the parent implementation first.
  48. */
  49. public function init()
  50. {
  51. if (!$this->hasModel() && $this->name === null) {
  52. throw new InvalidConfigException("Either 'name', or 'model' and 'attribute' properties must be specified.");
  53. }
  54. if (!isset($this->options['id'])) {
  55. $this->options['id'] = $this->hasModel() ? Html::getInputId($this->model, $this->attribute) : $this->getId();
  56. }
  57. parent::init();
  58. }
  59. /**
  60. * @return boolean whether this widget is associated with a data model.
  61. */
  62. protected function hasModel()
  63. {
  64. return $this->model instanceof Model && $this->attribute !== null;
  65. }
  66. }