如何在Drupal 10表格里嵌入form元素

By admin, 31 一月, 2024
use Drupal\Core\Form\FormStateInterface;
use Drupal\Core\Render\Element;

// Create a form element callback function to build the select element.
function custom_select_element_callback(array &$form, FormStateInterface $form_state) {
  // Define the select options.
  $options = [
    'option1' => 'Option 1',
    'option2' => 'Option 2',
    'option3' => 'Option 3',
  ];

  // Build the select element.
  $element = [
    '#type' => 'select',
    '#title' => t('Select an option'),
    '#options' => $options,
    '#default_value' => isset($form_state->getValue('custom_select')) ? $form_state->getValue('custom_select') : NULL,
  ];

  return $element;
}

// Create a form function to define the form structure.
function custom_form_example_form(array &$form, FormStateInterface $form_state) {
  // Initialize the table element.
  $form['table'] = [
    '#type' => 'table',
    '#caption' => t('Table with Select Element'),
    '#header' => [t('Column 1'), t('Column 2')],
  ];

  // Add row with select element in the first column.
  $form['table']['row1'] = [
    'column1' => [
      'select_element' => custom_select_element_callback($form, $form_state),
    ],
    'column2' => [
      // Example markup in column 2.
      '#markup' => 'Data for column 2',
    ],
  ];

  // Add more rows if needed.

  // Add a submit button.
  $form['submit'] = [
    '#type' => 'submit',
    '#value' => t('Submit'),
  ];

  return $form;
}

// Define a form submission function.
function custom_form_example_form_submit(array &$form, FormStateInterface $form_state) {
  // Handle form submission here.
}

标签

评论

Restricted HTML

  • 允许的HTML标签:<a href hreflang> <em> <strong> <cite> <blockquote cite> <code> <ul type> <ol start type> <li> <dl> <dt> <dd> <h2 id> <h3 id> <h4 id> <h5 id> <h6 id> <img src>
  • 自动断行和分段。
  • 网页和电子邮件地址自动转换为链接。
验证码
This question is for testing whether or not you are a human visitor and to prevent automated spam submissions.
请输入"Drupal10"

最新评论