mutual_credit-5.0.x-dev/modules/forms/src/Plugin/Block/FirstParty.php
modules/forms/src/Plugin/Block/FirstParty.php
<?php namespace Drupal\mcapi_forms\Plugin\Block; use Drupal\mcapi\Entity\Transaction; use Drupal\Core\Access\AccessResult; use Drupal\Core\Block\BlockBase; use Drupal\Core\Form\FormStateInterface; use Drupal\Core\Session\AccountInterface; use Drupal\Core\Entity\EntityFormBuilder; use Drupal\Core\Routing\CurrentRouteMatch; use Drupal\Core\Plugin\ContainerFactoryPluginInterface; use Symfony\Component\DependencyInjection\ContainerInterface; /** * Provides a designed transaction form. * * @Block( * id = "mcapi_1stparty", * admin_label = @Translation("Transaction form"), * category = @Translation("Community Accounting") * ) */ class FirstParty extends BlockBase implements ContainerFactoryPluginInterface{ /** * * @var EntityFormBuilder */ protected $entityFormBuilder; /** * * @var CurrentRouteMatch */ protected $currentRouteMatch; public function __construct($configuration, $plugin_id, $plugin_definition, EntityFormBuilder $entity_form_builder, CurrentRouteMatch $current_route_match) { parent::__construct($configuration, $plugin_id, $plugin_definition); $this->entityFormBuilder = $entity_form_builder; $this->currentRouteMatch = $current_route_match; } public static function create(ContainerInterface $container, array $configuration, $plugin_id, $plugin_definition) { return new static( $configuration, $plugin_id, $plugin_definition, $container->get('entity.form_builder'), $container->get('current_route_match') ); } /** * {@inheritdoc} */ public function build() { $transaction = Transaction::create(); $display_mode = $this->configuration['mode']; return $this->entityFormBuilder->getForm($transaction, $display_mode); } /** * {@inheritdoc} */ public function access(AccountInterface $account, $return_as_object = FALSE) { $access = parent::access($account, TRUE); if ($access->allowed()) { $route_name = $this->currentRouteMatch->getRouteName(); // Block is available if the main page is not already a transaction form. if (substr($route_name, 0, 14) == 'mcapi.1stparty') { $access = AccessResult::forbidden('Transaction form block does not show on the form page'); } // Or an operation form) elseif (substr($route_name, 0, 25) == 'entity.mcapi_transaction.') { $access = AccessResult::forbidden('Transaction forms do not show on transaction operation pages.'); } } return $return_as_object ? $access : $access->isAllowed(); } /** * {@inheritdoc} */ public function blockForm($form, FormStateInterface $form_state) { $form['mode'] = [ '#title' => t('Display'), '#type' => 'select', '#options' => array_map( function ($m) {return $m->label();}, mcapi_form_modes_load() ), '#default_value' => $this->configuration['mode']??key($options), ]; return $form; } /** * {@inheritdoc} */ public function blockSubmit($form, FormStateInterface $form_state) { $this->configuration['mode'] = $form_state->getValue('mode'); } }