improvements-2.x-dev/modules/improvements_contact/src/Plugin/Block/ContactFormBlock.php
modules/improvements_contact/src/Plugin/Block/ContactFormBlock.php
<?php namespace Drupal\improvements_contact\Plugin\Block; use Drupal\contact\Entity\ContactForm; use Drupal\Core\Block\BlockBase; use Drupal\Core\Entity\EntityFormBuilderInterface; use Drupal\Core\Entity\EntityTypeManagerInterface; use Drupal\Core\Form\FormStateInterface; use Drupal\Core\Plugin\ContainerFactoryPluginInterface; use Symfony\Component\DependencyInjection\ContainerInterface; /** * @Block( * id = "contact_form_block", * admin_label = @Translation("Contact form"), * category = @Translation("Forms"), * ) */ class ContactFormBlock extends BlockBase implements ContainerFactoryPluginInterface { protected EntityTypeManagerInterface $entityTypeManager; protected EntityFormBuilderInterface $entityFormBuilder; /** * Plugin constructor. */ public function __construct(array $configuration, $plugin_id, $plugin_definition, EntityTypeManagerInterface $entity_type_manager, EntityFormBuilderInterface $entity_form_builder) { parent::__construct($configuration, $plugin_id, $plugin_definition); $this->entityTypeManager = $entity_type_manager; $this->entityFormBuilder = $entity_form_builder; } /** * {@inheritdoc} */ public static function create(ContainerInterface $container, array $configuration, $plugin_id, $plugin_definition) { return new static( $configuration, $plugin_id, $plugin_definition, $container->get('entity_type.manager'), $container->get('entity.form_builder') ); } /** * {@inheritdoc} */ public function defaultConfiguration(): array { return [ 'contact_form_id' => '', ]; } /** * {@inheritDoc} */ public function blockForm($form, FormStateInterface $form_state): array { $options = []; foreach (ContactForm::loadMultiple() as $contact_form_id => $contact_form) { $options[$contact_form_id] = $contact_form->label(); } $form['contact_form_id'] = [ '#type' => 'select', '#title' => $this->t('Contact form'), '#options' => $options, '#required' => TRUE, '#default_value' => $this->configuration['contact_form_id'], ]; return $form; } /** * {@inheritdoc} */ public function blockSubmit($form, FormStateInterface $form_state): void { $this->configuration['contact_form_id'] = $form_state->getValue('contact_form_id'); } /** * {@inheritDoc} */ public function build(): array { $form = []; if ($this->configuration['contact_form_id']) { $contact_message = $this->entityTypeManager->getStorage('contact_message')->create([ 'contact_form' => $this->configuration['contact_form_id'], ]); $form = $this->entityFormBuilder->getForm($contact_message); $form['#cache']['contexts'][] = 'user.permissions'; } return [ 'content' => $form, ]; } }