Drupal → Создание табличной формы с возможностью сортировки

01.05.2019

Пример формы для сортировки нод по полю field_weight

class ExampleDraggableForm extends FormBase {

  /**
   * {@inheritdoc}
   */
  public function getFormId() {
    return 'example_draggable_form';
  }

  /**
   * {@inheritdoc}
   */
  public function buildForm(array $form, FormStateInterface $form_state) {
    $form['table'] = [
      '#type' => 'table',
      '#header' => ['Title', 'Weight'],
      '#empty' => 'Empty...',
      '#tabledrag' => [[
        'action' => 'order',
        'relationship' => 'sibling',
        'group' => 'node-weight',
      ]],
    ];

    $entity_query = \Drupal::entityQuery('node');
    $entity_query->sort('field_weight');
    $nids = $entity_query->execute();
    $nodes = Node::loadMultiple($nids);

    foreach ($nodes as $nid => $node) {
      $form['table'][$nid] = [
        '#attributes' => [
          'class' => ['draggable'],
        ],
        '#weight' => $nid->get('field_weight')->value,
      ];

      $form['table'][$nid]['title'] = [
        '#markup' => $node->label(),
      ];

      $form['table'][$nid]['weight'] = [
        '#type' => 'weight',
        '#delta' => 50,
        '#default_value' => $node->get('field_weight')->value,
        '#attributes' => [
          'class' => ['node-weight'],
        ],
      ];
    }

    $form['submit'] = [
      '#type' => 'submit',
      '#value' => 'Save',
    ];

    return $form;
  }

  /**
   * {@inheritdoc}
   */
  public function submitForm(array &$form, FormStateInterface $form_state) {
    $table_values = $form_state->getValue('table');
    foreach ($table_values as $nid => $row_values) {
      $node = Node::load($nid);
      $node->set('field_weight', $row_values['weight']);
      $node->save();
    }
  }

}
Написанное актуально для
Drupal 8
Похожие записи

Добавить комментарий