I have defined a content type that includes a custom field called index. That gives the indexposition to show the item in the total list of items (aka a sort of weight). How can I use Drupal Draggable Views to update my custom index field in my content whenever I drag the item to a new position?

It is important that is my custom field index because I am reading the content out of Drupal using the json:api module

Comments

wombatbuddy’s picture

1. What is the name of content type that has the 'index' field?
2. What is the name of the view?

HixField’s picture

The content type represents an "Package" (nothing todo with any drupal or other package!)  and contains the following other fields:

  • Id: text, plain
  • index: number (this is the field I'm talking about)
  • payable: Boolean

I'm displaying this in a table, and would just like the option to drag it around and then update the index field:

wombatbuddy’s picture

Here is the solution with the custom code. In the example the draggable view name is the 'packages_order' and the display is the 'page_1'.

use Drupal\Core\Form\FormStateInterface;

/**
 * Implements hook_form_alter().
 */
function my_module_form_alter(&$form, FormStateInterface $form_state, $form_id) {
  // The name and display of the draggable view.
  $view_name = 'packages_order';
  $display_name = 'page_1';
  // The id of the draggableviews form (that contains the 'Save order' button).
  $view_form_id = 'views_form_' . $view_name . '_' . $display_name;

  if ($view_form_id != $form_id) {
    return;
  }
  // Add the custom submit hanler (fired when a user click on the 'Save order').
  $form['actions']['save_order']['#submit'][] = 'my_module_draggableviews_views_submit';
}

/**
 * Custom form submit handler.
 */
function my_module_draggableviews_views_submit(&$form, FormStateInterface $form_state) {
  $input = $form_state->getUserInput();

  foreach ($input['draggableviews'] as $item) {

    $nid = $item['id'];
    $weight = $item['weight'];
    $node = \Drupal::entityTypeManager()->getStorage('node')->load($nid);

    if ($node) {
      $node->set('field_index', $weight);
      $node->save();
    }
  }
}
HixField’s picture

Thanks a lot! I have never programmed in php before (was hoping for a contrib module) but I have experience with development and php I will have a look at your code. Thanks!

asela34’s picture

Hello, how can I get the draggableview weight field value and save it to content field called "field_priority" ? I have a custom developed module using which use to search FAQs from the front-end. Without reloading the page. 

https://drupal.stackexchange.com/questions/312392/save-draggableview-weight