Commit 90d9d8e7 authored by Xano's avatar Xano Committed by bojanz

Allow element callbacks to be regular plugin methods. Update PriceDefaultWidget.

Approach taken from Bart Feenstra's Currency module.
parent 56d20062
......@@ -7,6 +7,7 @@
namespace Drupal\commerce_price\Plugin\Field\FieldWidget;
use Drupal\commerce\PluginCallbackTrait;
use Drupal\commerce_price\NumberFormatterFactoryInterface;
use Drupal\Core\Entity\EntityManagerInterface;
use Drupal\Core\Field\FieldDefinitionInterface;
......@@ -30,6 +31,8 @@ use Symfony\Component\DependencyInjection\ContainerInterface;
*/
class PriceDefaultWidget extends WidgetBase implements ContainerFactoryPluginInterface {
use PluginCallbackTrait;
/**
* The currency storage.
*
......@@ -110,7 +113,7 @@ class PriceDefaultWidget extends WidgetBase implements ContainerFactoryPluginInt
$element['#attached']['library'][] = 'commerce_price/admin';
$element['#element_validate'] = [
[get_class($this), 'validateElement'],
[get_class($this), 'instantiate#field.widget#' . $this->getPluginId() . '#validateElement'],
];
$element['amount'] = [
'#type' => 'textfield',
......@@ -154,18 +157,14 @@ class PriceDefaultWidget extends WidgetBase implements ContainerFactoryPluginInt
/**
* Converts the amount back to the standard format (e.g. "9,99" -> "9.99").
*/
public static function validateElement(array $element, FormStateInterface $formState) {
// @todo Fix this.
$currencyStorage = \Drupal::service('entity.manager')->getStorage('commerce_currency');
$numberFormatter = \Drupal::service('commerce_price.number_formatter_factory')->createInstance();
public function validateElement(array $element, FormStateInterface $formState) {
$value = $formState->getValue($element['#parents']);
if (empty($value['amount'])) {
return;
}
$currency = $currencyStorage->load($value['currency_code']);
$value['amount'] = $numberFormatter->parseCurrency($value['amount'], $currency);
$currency = $this->currencyStorage->load($value['currency_code']);
$value['amount'] = $this->numberFormatter->parseCurrency($value['amount'], $currency);
if ($value['amount'] === FALSE) {
$formState->setError($element['amount'], t('%title is not numeric.', [
'%title' => $element['#title'],
......
<?php
/**
* @file
* Contains \Drupal\commerce\PluginCallbackTrait.
*/
namespace Drupal\commerce;
trait PluginCallbackTrait {
/**
* Instantiates the current plugin class and calls a method on it.
*/
public static function __callStatic($name, array $arguments) {
if (preg_match('/^instantiate#(.+?)#(.+?)$/', $name)) {
list(, $pluginType, $pluginId, $method) = explode('#', $name);
/** @var \Drupal\Component\Plugin\PluginManagerInterface $manager */
$manager = \Drupal::service('plugin.manager.' . $pluginType);
$plugin = $manager->createInstance($pluginId);
return call_user_func_array([$plugin, $method], $arguments);
}
}
}
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment