MailingListSubscribeBlock.php in Mailgun 8
File
modules/mailgun_mailing_lists/src/Plugin/Block/MailingListSubscribeBlock.php
View source
<?php
namespace Drupal\mailgun_mailing_lists\Plugin\Block;
use Drupal\Core\Block\BlockBase;
use Drupal\Core\Form\FormBuilderInterface;
use Drupal\Core\Form\FormStateInterface;
use Drupal\Core\Plugin\ContainerFactoryPluginInterface;
use Symfony\Component\DependencyInjection\ContainerInterface;
use Mailgun\Mailgun;
use Drupal\mailgun_mailing_lists\Form\MailingListSubscribeForm;
class MailingListSubscribeBlock extends BlockBase implements ContainerFactoryPluginInterface {
protected $mailgunClient;
protected $formBuilder;
public static function create(ContainerInterface $container, array $configuration, $plugin_id, $plugin_definition) {
return new static($configuration, $plugin_id, $plugin_definition, $container
->get('mailgun.mailgun_client'), $container
->get('form_builder'));
}
public function __construct(array $configuration, $plugin_id, $plugin_definition, Mailgun $mailgun_client, FormBuilderInterface $form_builder) {
parent::__construct($configuration, $plugin_id, $plugin_definition);
$this->mailgunClient = $mailgun_client;
$this->formBuilder = $form_builder;
}
public function build() {
$config = $this
->getConfiguration();
$form = new MailingListSubscribeForm($this->mailgunClient, $config['mailing_list']);
return $this->formBuilder
->getForm($form);
}
public function label() {
$config = $this
->getConfiguration();
if (!empty($config['mailing_list'])) {
$name = $this->mailgunClient
->mailingList()
->show($config['mailing_list'])
->getList()
->getName();
return $this
->t('Subscribe to @name', [
'@name' => $name,
]);
}
return parent::label();
}
public function blockForm($form, FormStateInterface $form_state) {
$form = parent::blockForm($form, $form_state);
$config = $this
->getConfiguration();
$lists = $this->mailgunClient
->mailingList()
->pages()
->getLists();
$options = [
'' => $this
->t('- None -'),
];
foreach ((array) $lists as $list) {
$options[$list
->getAddress()] = $list
->getName();
}
$form['mailing_list'] = [
'#type' => 'select',
'#title' => $this
->t('Mailing list'),
'#options' => $options,
'#default_value' => isset($config['mailing_list']) ? $config['mailing_list'] : '',
'#required' => TRUE,
];
return $form;
}
public function blockSubmit($form, FormStateInterface $form_state) {
parent::blockSubmit($form, $form_state);
$this->configuration['mailing_list'] = $form_state
->getValue('mailing_list');
}
}