3 namespace Drupal\language\Form;
5 use Drupal\Component\Utility\Html;
6 use Drupal\Core\Entity\EntityForm;
7 use Drupal\Core\Form\FormStateInterface;
8 use Drupal\Core\Language\LanguageInterface;
9 use Drupal\language\ConfigurableLanguageManagerInterface;
10 use Symfony\Component\DependencyInjection\ContainerInterface;
13 * Base form for language add and edit forms.
15 abstract class LanguageFormBase extends EntityForm {
18 * The configurable language manager.
20 * @var \Drupal\language\ConfigurableLanguageManagerInterface
22 protected $languageManager;
25 * Constructs a ContentEntityForm object.
27 * @param \Drupal\language\ConfigurableLanguageManagerInterface $language_manager
28 * The configurable language manager.
30 public function __construct(ConfigurableLanguageManagerInterface $language_manager) {
31 $this->languageManager = $language_manager;
37 public static function create(ContainerInterface $container) {
39 $container->get('language_manager')
44 * Common elements of the language addition and editing form.
46 public function commonForm(array &$form) {
47 /* @var $language \Drupal\language\ConfigurableLanguageInterface */
48 $language = $this->entity;
49 if ($language->getId()) {
50 $form['langcode_view'] = [
52 '#title' => $this->t('Language code'),
53 '#markup' => $language->id()
57 '#value' => $language->id()
62 '#type' => 'textfield',
63 '#title' => $this->t('Language code'),
66 '#default_value' => '',
68 '#description' => $this->t('Use language codes as <a href=":w3ctags">defined by the W3C</a> for interoperability. <em>Examples: "en", "en-gb" and "zh-hant".</em>', [':w3ctags' => 'http://www.w3.org/International/articles/language-tags/']),
72 '#type' => 'textfield',
73 '#title' => $this->t('Language name'),
75 '#default_value' => $language->label(),
78 $form['direction'] = [
80 '#title' => $this->t('Direction'),
82 '#description' => $this->t('Direction that text in this language is presented.'),
83 '#default_value' => $language->getDirection(),
85 LanguageInterface::DIRECTION_LTR => $this->t('Left to right'),
86 LanguageInterface::DIRECTION_RTL => $this->t('Right to left'),
94 * Validates the language editing element.
96 public function validateCommon(array $form, FormStateInterface $form_state) {
97 // Ensure sane field values for langcode and name.
98 if (!isset($form['langcode_view']) && !preg_match('@^[a-zA-Z]{1,8}(-[a-zA-Z0-9]{1,8})*$@', $form_state->getValue('langcode'))) {
99 $form_state->setErrorByName('langcode', $this->t('%field must be a valid language tag as <a href=":url">defined by the W3C</a>.', [
100 '%field' => $form['langcode']['#title'],
101 ':url' => 'http://www.w3.org/International/articles/language-tags/',
104 if ($form_state->getValue('label') != Html::escape($form_state->getValue('label'))) {
105 $form_state->setErrorByName('label', $this->t('%field cannot contain any markup.', ['%field' => $form['label']['#title']]));