8 – Sorting Views result rows based on an array of node IDs

I have a View of song nodes, and each node has a programmatically calculated total number of points associated with it. (For background: song nodes are referenced in a custom field_chart_items field on a chart node, hence the $chartHistory node query seen in the hook below. The custom field includes a numeric Position that’s entered on the chart node, and a numeric Points total that’s hidden from view and calculated based on Position in a chart_field_entity_presave() hook.) I’m trying to sort the View’s results by points, with highest points totals listed first.

In a views_pre_render() hook, I calculate the points total for each row and place it into an array, $songAndPoints, that contains the song’s nid and points total. The array is sorted so that the song with the highest points total comes first – therefore, the order of the nids in the array is the order in which I want my results to appear.

Can I programmatically reorder the $view->result array based on the array of nids I’m getting? My attempt below, using a uasort() callback, doesn’t work, but I’m not sure if or how I can do what I’m looking for (or if, perhaps, it needs to happen in a different hook).

 * Implements hook_views_pre_render().
function MODULE_views_pre_render(&$view) {
  if ($view->current_display === 'DISPLAYID'
    && $view->id() === 'VIEWID') {
      $entity_type_manager = Drupal::entityTypeManager();
      $node_storage = $entity_type_manager->getStorage('node');  

      foreach ($view->result as $key => $song) {
        $node_type = 'chart';
        $songNID = $song->nid;
        $chartHistory = $node_storage->getQuery()
          ->condition('type', $node_type)
          ->condition('field_chart_items', $songNID, 'IN')
          ->condition('status', 1)

        if ($chartHistory) {
          foreach ($chartHistory as $chartNID) {
            // ...
            // Various calculations to get points total, $songPoints, for each song.
            // ...
          $songAndPoints($key) = ('points' => $songPoints, 'nid' => $songNID);

          // Sort based on point values.

        } else {
          $songAndPoints() = ('points' => 0, 'nid' => $songNID);

      kint($songAndPoints); // Array with original row number as key and two values, points and NID, sorted with highest points first. This is how I want to sort the results.

      uasort($view->result, "MODULE_sort_by_points_total");

 * Custom uasort() callback to sort view results by points totals.
function MODULE_sort_by_points_total($left, $right) {
    $order = ('704', '712', '707', '713', '711', '709', '708', '883', '882', '715', '714', '710', '705'); // TEMPORARY: Hardcoded list of node IDs in order; should be replaced by something like array_column($songAndPoints, 'nid'), but hardcoded values don't work either.

    $flipped = array_flip($order);
    $leftPos = $flipped($left)->nid;
    $rightPos = $flipped($right)->nid;
    return $leftPos >= $rightPos;
    // via https://stackoverflow.com/questions/17324708/php-array-multisort-not-sorting-my-multidimensional-array-as-expected/17325584#17325584

Organic instant start YouTube video promotion via seo marketing for $24

Organic instant start YouTube video promotion via seo marketing

get provide 10,000 YouTube video views

And get ultimate usa, uk, canada, europ and worldwide target organic YouTube promotion.

are you except to get 100% safe ,real and effective YouTube promotion, without any type of scam/bots? so of course, this is 100% right service for you. we use the best strategies to market your content to both target and organic audience.

This is a professional YouTube video promotion with massive engagement.

Benefit of my service

use real and organic method

100% safe and worldwide audience

Delivery on time

increase your popularity on YouTube

making your video more popularty

note:- Check out my gig extra for more promotion.


8 – How to set default value of views exposed filter programmatically?

I seen many answers for D7, but I cant find an information for D8/9.

If write in form_alter hook

$form['field_assigned_location_target_id']['#default_value'] = '553';

This does not affect at all. So default value from view settings is always used instead.

If I write

$form['field_assigned_location_target_id']['#value'] = '553';

This affects on value initially displayed on the filter, but this value is used and applied always, not only as a default value but on any form submission disregarding value set in form by user.

Post views counter being cached by litespeed cache plugin

I use post views counter in amp page using this code: do_shortcode('(post-views)');

Problem is: litespeed cache plugin cached it. I read this documentation.

So I tried use do_shortcode('(esi post-views)');

It’s not working?

Can anyone tell me how can I achieve this?

Thank you.

8 – Writing PHP into views field template twig

I’m less familiar with D8, but I need to re-write a views field output using some PHP. I’ve made a custom field template HTML.twig file, but I’m not sure what I need to do to be able to run a PHP execution on my field to render it out as I want.


I am trying to run a function on the User ID as I have a module which hashes it before sending it to an external platform, however, now the client wants the understand which user is which, and the only way I can think to do this is by performing the same hashing code on the User ID in a format I can easily cross reference the user with their hashed output

I have a very basic view table showing only the User ID and email address, and I’ve managed to create a views field override using this page which has overwritten my field successfully. But now I want to run a command I’m going to copy from my contrib module, the below to be specific, so that I can work out which User ID relates to which hashed code

return Crypt::hmacBase64($uid, Drupal::service('private_key')->get() . Settings::getHashSalt());

views – Debugging Pager when it isn’t showing

I have been looking for tips to debug the Pager when it doesn’t show and I have not really found anything as of yet. We have only 1 view that is not displaying the pager in our view no matter what we do. When we test for $pager it is not present at all in the view.

We have the pager turned on on the view but it does not show. Our query returns the results we expect and if we change the url to have page=1, page=2 the results change, however like I have said the pager does not show.

So if anyone has any advice on how to do debug the pager it would be great as at this point I am totally lost.

Order By Multi Select Choice List on SharePoint Views

Unfortunately, we cannot sort the multichoice columns. Some workarounds:


For each choice, create a new “Yes/No” column. For example, if you have Red, Green, Blue choices, then create new three columns:

  • Name: Red, Type: Yes/No
  • Name: Green, Type: Yes/No
  • Name: Blue, Type: Yes/No

Then you can sort and filter by individual columns you have create.

commerce – Display price on Views for product variation

I’m confused, how to display on Views just one price for product with variations? I have product with 2 variation, and both prices are displayed, like:
Price: 1-Price for 1-Variation-Product , Price: 2-Price for 2-Variation-Product

The both prices are the same, in addition.
How best way to manage it?
I have Drupal 9, Commerce 2

8 – Twig: Generate classname from variable in views template

In the twig template file of a view with grouped rows I would like to add the title of the group as a classname. But the rendered classname from title variable is just “_” on every group. This is the generated html code of the group with title “1”:

<h3 class="views-group group-_">*1*</h3>

What’s wrong here? Please see my template code:

* @file
* Default theme implementation to display a view of unformatted rows.
* Available variables:
* - title: The title of this group of rows. May be empty.
* - rows: A list of the view's row items.
*   - attributes: The row's HTML attributes.
*   - content: The row's content.
* - view: The view object.
* - default_row_class: A flag indicating whether default classes should be
*   used on rows.
* @see template_preprocess_views_view_unformatted()
* @ingroup themeable
{% if title %}
    set classes = (
      'group-' ~ title|clean_class,
  <h3{{ content_attributes.addClass(classes) }}>*{{ title }}*</h3>
{% endif %}
{% for row in rows %}
    set row_classes = (
      default_row_class ? 'views-row',
  <div{{ row.attributes.addClass(row_classes) }}>
    {{- row.content -}}
{% endfor %}

python – Dificuldade com django e views com base em oop

Eu estou tendo um problema em criar uma pagina para criar novos produtos e sei que estou tendo algum problema com oop por falta de experiência. Eu gostaria de passar o valor de self neste caso sendo “self==Product” mas acabou passando “self==Creat_view” e não sei oq estou fazendo de errado. (a indentação das classes estão corretas no programa(-1 tab), só o código que não cola direito aqui)

form_class_mapping = {'Product':ProductModelForm,'Gondola':ProdGondolaModelForm,'Stock':ProdStockModelForm}

class List_view(ListView):
template_name ='templates/list.html'

def __init__(self):
    queryset = self.objects.all()

class Creat_view(CreateView):
template_name ='templates/create.html'

def __init__(self):
    queryset = self.objects.all()
    self.form_class = form_class_mapping(self)

def form_valid(self,form):
    return super().form_valid(form)

Aqui estão minhas urls:

app_name = 'Product'
urlpatterns = (
path('', List_view.as_view(),name="Product-list"),
path('create/', Creat_view.as_view(),name="Product-create"),
path('<int:id>/update/', Update_view.as_view(),name="Product-update"),
path('<int:id>/delete/', Delete_view.as_view(),name="Product-delete")


E meu erro é:

  File "C:UsersuserdevcmssgiStockManagementviews.py", line 22, in __init__
queryset = self.objects.all()
AttributeError: 'Creat_view' object has no attribute 'objects'