0

I have the following code to alter a view and filter IN only specific nodes

function MYMODULE_views_query_alter(ViewExecutable $view, QueryPluginBase $query) {
  if($view->id() == 'myview'){
    foreach ($query->where as &$condition_group) {
      foreach ($condition_group['conditions'] as &$condition) {
        if ($condition['field'] == "node_field_data.nid") {
          $condition = array(
            'field' => "node_field_data.nid",
            'value' => [2,4,6,1,3,5],
            'operator' => 'in',
          );
          break;
        }
      }
    } 
    //this does not work    
    //$query->addOrderBy('node_field_data','nid', 'ASC', '', [2,4,6,1,3,5]);    
  }
}

and I want to sort them with this specific order [2,4,6,1,3,5]

I tried not putting any sorting field but the view sorts the nodes by created date. How can I tell the view to sort them in this manner ?

I think I need to use ORDER BY FIELD('node_field_data'.'nid','2','4','6','1','3','5') in sql but I don't know how its done in drupal

I have seen this answer but don't know how it applies to my case

any help would be appreciated

0

OK I figured it out

$query->addOrderBy(NULL, 'FIELD(node_field_data.nid,2,4,6,1,3,5)', 'ASC', 'order_field');
  • What is 'order_field' here? already node_field_data.nid has been specified in FIELD. What should I give in 'order_field'? – siddiq Jul 19 '18 at 1:45
  • @siddiq order_field is an (optional) alias - for me, it was necessary because my $field is a formula. I also found it necessary to remove all sort criteria under the View's UI for it to work. – vrwired Aug 21 at 19:15

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.