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.
}
评论