【问题标题】:How to create multiple fields of the same name and get its' values when submitting in Drupal 8?在 Drupal 8 中提交时如何创建多个同名字段并获取其值?
【发布时间】:2018-05-29 21:19:48
【问题描述】:

下面是我在 Drupal 8 中自定义模块的配置表单。

<?php
 namespance Drupal\hello_world\Form;

 class MailForm extends ConfigFormBase {

   public function buildForm(array $form, FormStateInterface $form_state) {

     $form = parent::buildForm($form, $form_state);

     $form['email_address'] = [
       '#type' => 'email',
       '#title' => $this->t(
         'Email address:'
       ),
     ];

     return $form;
   }

   public function submitForm(array &$form, FormStateInterface $form_state) {

     $email_address = $form_state->getValue('email_address');

   }
 }

如何在 Drupal 8 中创建多个同名的输入字段?

<input name="email_address[]" type="email" />
<input name="email_address[]" type="email"  />
<input name="email_address[]" type="email" />

在 Drupal 8 中提交时,如何从上述输入字段中获取所有值,如下所示?

array(
  'email_address' => array(
    '0' => 'a@email.com',
    '1' => 'b@email.com',
    '2' => 'c@email.com',
  )
)

【问题讨论】:

    标签: php forms module submit drupal-8


    【解决方案1】:

    创建两级数组并使用'#tree' =&gt; TRUE 选项:

    $form['email_address'] = [
      '#type' => 'fieldset',
      '#tree' => TRUE,
      '#title' => $this->t('Email address:'),
      '0' => [
        '#type' => 'email',
        '#title' => $this->t('First'),
      ],
      '1' => [
        '#type' => 'email',
        '#title' => $this->t('First'),
      ],
    ];
    

    我唯一不能完全确定的(因为我没有检查过这段代码)是电子邮件元素的数字索引。如果它有效,请发表评论。如果没有 - 使用字符串。

    【讨论】:

    • 提交表单时如何获取这些输入的值?
    • $form_state->getValue('email_address') 应该返回一个值数组
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-03-29
    • 2017-03-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多