field_completeness-1.0.3/src/Form/FieldCompletenessSettingsForm.php
src/Form/FieldCompletenessSettingsForm.php
<?php
namespace Drupal\field_completeness\Form;
use Drupal\Core\Form\ConfigFormBase;
use Drupal\Core\Form\FormStateInterface;
use Drupal\Core\Url;
use Drupal\Core\Link;
/**
* Configure Field completeness settings for this site.
*
* @internal
*/
class FieldCompletenessSettingsForm extends ConfigFormBase {
/**
* Config settings.
*
* @var string
*/
const SETTINGS = 'field_completeness.settings';
/**
* {@inheritdoc}
*/
public function getFormId() {
return 'fc_admin_settings';
}
/**
* {@inheritdoc}
*/
protected function getEditableConfigNames() {
return [
static::SETTINGS,
];
}
/**
* {@inheritdoc}
*/
public function buildForm(array $form, FormStateInterface $form_state) {
$types = node_type_get_names();
$config = $this->config(static::SETTINGS);
$options = [];
$url = "";
$link = "";
$selected_value = [];
$header = [
'type_name' => $this->t('Content type'),
'operations' => $this->t(''),
];
foreach ($types as $type_name => $type_text) {
$url = Url::fromRoute('field_completeness.edit', ['node_type' => $type_name]);
$link = Link::fromTextAndUrl($this->t('Edit'), $url);
$options[$type_name] = ['type_name' => $type_text, 'operations' => $this->t('')];
}
if (NULL !== $config->get('allowed_types')) {
foreach ($config->get('allowed_types') as $bundle) {
$selected_value[$bundle] = $bundle;
}
}
$form['fc_allowed_types'] = [
'#type' => 'tableselect',
'#title' => $this->t('Content types allowed in field completeness'),
'#header' => $header,
'#options' => $options,
'#default_value' => $selected_value,
'#empty' => $this->t('No bundle found'),
];
return parent::buildForm($form, $form_state);
}
/**
* {@inheritdoc}
*/
public function validateForm(array &$form, FormStateInterface $form_state) {
if ($form_state->isValueEmpty(['fc_allowed_types'])) {
$form_state->setErrorByName('fc_allowed_types', $this->t('The content type for the field completeness must be one of those selected as an allowed field completeness type.'));
}
parent::validateForm($form, $form_state);
}
/**
* {@inheritdoc}
*/
public function submitForm(array &$form, FormStateInterface $form_state) {
$allowed_types = array_filter($form_state->getValue('fc_allowed_types'));
// We need to save the allowed types in an array ordered by machine_name so
// that we can save them in the correct order if node type changes.
sort($allowed_types);
$this->config(static::SETTINGS)
//Remove unchecked types
->set('allowed_types', $allowed_types)
->save();
parent::submitForm($form, $form_state);
}
}
