mutual_credit-5.0.x-dev/src/Plugin/Field/FieldWidget/Worth.php

src/Plugin/Field/FieldWidget/Worth.php
<?php

namespace Drupal\mcapi\Plugin\Field\FieldWidget;

use Drupal\Core\Field\Attribute\FieldWidget;
use Drupal\Core\Field\WidgetBase;
use Drupal\Core\Field\FieldItemListInterface;
use Drupal\Core\Form\FormStateInterface;
use Drupal\Core\Render\Markup;
use Drupal\Core\StringTranslation\TranslatableMarkup;

/**
 * Plugin implementation of worth widget.
 */
#[FieldWidget(
  id: 'mc_worth_nullable',
  label: new TranslatableMarkup('Worth'),
  description: new TranslatableMarkup('Main entry formatted with Twig'),
  field_types: [
    'mc_worth'
  ],
  multiple_values: FALSE
)]
class Worth extends WidgetBase {

  /**
   * {@inheritDoc}
   */
  public function formElement(FieldItemListInterface $items, $delta, array $element, array &$form, FormStateInterface $form_state) {
    $element = [
      'value' => $element + [
        '#type' => 'worth',
        '#default_value' => $items[$delta]->value,
        '#min' => 0,
        '#minus' => $this->fieldDefinition->getSetting('minus')
      ]
    ];

    if (is_numeric($items[$delta]->value)) {
      $element['reset'] = [
        '#type' => 'button',
        '#name' => $items->getName(),
        '#value' => Markup::Create('<a href="#">'.t('Revert to default...').'</a>'),
        '#ajax' => [
          'callback' => [$this, 'unsetPersonalLimits'],
          'wrapper' => 'edit-'.$items->getName().'-wrapper',
          'effect' => 'fade',
        ],
        // Make the button appear as a link.
        '#weight' => 2,
      ];
    }
    return $element;
  }

  /**
   * @note This isn't really part of this form and the ajax that calls it isn't really form API.
   */
  function unsetPersonalLimits($form, FormStateInterface $form_state) {
    $field_name = $form_state->getTriggeringElement()['#name'];
    $wid = $form_state->getFormObject()->getEntity()->id();
    \Drupal::database()->delete('mc_wallet__'.$field_name)
      ->condition('entity_id', $wid)
      ->execute();
    unset($form[$field_name]['widget'][0]['reset']);
    $form[$field_name]['widget'][0]['value']['main']['#default_value'] = '';
    $form[$field_name]['widget'][0]['value']['main']['#value'] = '';
    \Drupal::cache('entity')->delete('values:mc_wallet:'.$wid);
    return $form[$field_name];
  }

}

Главная | Обратная связь

drupal hosting | друпал хостинг | it patrol .inc