Magento 2 Documentation  2.3
Documentation for Magento 2 CMS v2.3 (December 2018)
Button.php
Go to the documentation of this file.
1 <?php
7 
10 
14 class Button extends Template implements ControlInterface
15 {
21  protected function _construct()
22  {
23  $this->setTemplate($this->getTemplatePath());
24 
25  parent::_construct();
26  }
27 
33  protected function getTemplatePath()
34  {
35  return 'Magento_Ui::control/button/default.phtml';
36  }
37 
43  public function getType()
44  {
45  if (in_array($this->getData('type'), ['reset', 'submit'])) {
46  return $this->getData('type');
47  }
48 
49  return 'button';
50  }
51 
57  public function getAttributesHtml()
58  {
59  $disabled = $this->getDisabled() ? 'disabled' : '';
60  $title = $this->getTitle();
61  if (empty($title)) {
62  $title = $this->getLabel();
63  }
64  $classes = ['action-', 'scalable'];
65  if ($this->hasData('class')) {
66  $classes[] = $this->getClass();
67  }
68  if ($disabled) {
69  $classes[] = $disabled;
70  }
71 
72  return $this->attributesToHtml($this->prepareAttributes($title, $classes, $disabled));
73  }
74 
80  public function getOnClick()
81  {
82  if ($this->hasData('on_click')) {
83  return $this->getData('on_click');
84  } else {
85  $url = $this->hasData('url') ? $this->getData('url') : $this->getUrl();
86  if (!empty($url)) {
87  return sprintf("location.href = '%s';", $url);
88  }
89 
90  return null;
91  }
92  }
93 
102  protected function prepareAttributes($title, $classes, $disabled)
103  {
104  $attributes = [
105  'id' => $this->getId(),
106  'name' => $this->getElementName(),
107  'title' => $title,
108  'type' => $this->getType(),
109  'class' => implode(' ', $classes),
110  'onclick' => $this->getOnClick(),
111  'style' => $this->getStyle(),
112  'value' => $this->getValue(),
113  'disabled' => $disabled,
114  ];
115  if ($this->getDataAttribute()) {
116  foreach ($this->getDataAttribute() as $key => $attr) {
117  $attributes['data-' . $key] = is_scalar($attr) ? $attr : json_encode($attr);
118  }
119  }
120 
121  return $attributes;
122  }
123 
130  protected function attributesToHtml($attributes)
131  {
132  $html = '';
133  foreach ($attributes as $attributeKey => $attributeValue) {
134  if ($attributeValue === null || $attributeValue == '') {
135  continue;
136  }
137  $html .= $attributeKey . '="' . $this->escapeHtmlAttr($attributeValue, false) . '" ';
138  }
139 
140  return $html;
141  }
142 }
$title
Definition: default.phtml:14
getData($key='', $index=null)
Definition: DataObject.php:119
$attr
Definition: text.phtml:8
prepareAttributes($title, $classes, $disabled)
Definition: Button.php:102
$attributes
Definition: matrix.phtml:13
escapeHtmlAttr($string, $escapeSingleQuote=true)