contextly-8.x-2.1/src/Form/ContextlyImageAdminForm.php
src/Form/ContextlyImageAdminForm.php
<?php
namespace Drupal\contextly\Form;
use Drupal\Core\DependencyInjection\ContainerInjectionInterface;
use Drupal\Core\Form\ConfigFormBase;
use Drupal\Core\Form\FormStateInterface;
use Drupal\node\Entity\NodeType;
use Symfony\Component\DependencyInjection\ContainerInterface;
/**
* The ContextlyImageAdminForm class.
*/
class ContextlyImageAdminForm extends ConfigFormBase implements ContainerInjectionInterface {
/**
* The contextly base service.
*
* @var \Drupal\contextly\ContextlyBaseServiceInterface
*/
protected $contextlyBase;
/**
* {@inheritdoc}
*/
public static function create(ContainerInterface $container) {
$instance = parent::create($container);
$instance->contextlyBase = $container->get('contextly.base');
return $instance;
}
/**
* {@inheritdoc}
*/
protected function getEditableConfigNames() {
return [
'contextly.contextlyimageadmin',
];
}
/**
* {@inheritdoc}
*/
public function getFormId() {
return 'contextly_image_admin_form';
}
/**
* {@inheritdoc}
*/
public function buildForm(array $form,
FormStateInterface $form_state) {
$available_fields = $this->contextlyBase
->settingsGetAvailableFields(['image']);
if (empty($available_fields)) {
$this->messenger
->addWarning($this->t('Add some image fields to Contextly-enabled node types to use featured images.'));
return $form;
}
$config = $this->config('contextly.contextlyimageadmin');
$form['images'] = [
'#type' => 'details',
'#title' => $this->t('Featured images'),
'#open' => TRUE,
];
$count = count($available_fields);
$these_fields = $this->stringTranslation
->formatPlural($count, 'This field lets', 'These fields let');
$form['images']['info'] = [
'#type' => 'item',
'#markup' => $this->t('@these_fields you control what images will be used to create the thumbnails for Contextly recommendations. The first image from the selected field below will be used to create the thumbnail.',
['@these_fields' => $these_fields]
),
// @todo Move to help.
];
$node_types = NodeType::loadMultiple();
foreach ($available_fields as $type => $fields) {
$options = $fields;
$node_type = $node_types[$type];
$form['images']['contextly_featured_image__' . $type] = [
'#type' => 'select',
'#title' => $node_type->label(),
'#options' => $options,
'#empty_value' => '',
'#default_value' => $config->get('contextly_featured_image__' . $type) ?: '',
];
}
return parent::buildForm($form, $form_state);
}
/**
* {@inheritdoc}
*/
public function submitForm(array &$form,
FormStateInterface $form_state) {
parent::submitForm($form, $form_state);
$config = $this->config('contextly.contextlyimageadmin');
$available_fields = $this->contextlyBase
->settingsGetAvailableFields(['image']);
// $node_types = NodeType::loadMultiple();
foreach ($available_fields as $type => $fields) {
$config->set('contextly_featured_image__' . $type,
$form_state->getValue('contextly_featured_image__' . $type));
}
$config->save();
}
}
