0

I'm using Views to create a view which shows list of contents. The requirements of the view is something like this:

  • The page display url must be /mycontents
  • The contents must be filtered by current user(The content's author must be current user).

And what I did:

  • Set Page settings > Path to /mycontents
  • In Advanced > Contextual Filters , add Authored by
  • In the contextual filter's When the default value is not in the url section, checked Provide default value and selected User ID from logged in user.

The problem is that after saving the view, the actual url of the view becomes /mycontens/{uid}. Is there any way to remove the {uid} from the path?

1

I don't think this is possible if you show the view as a page, but you might be able to solve the problem by creating a custom route and rendering the view on that page, where you fetch the uid programatically.

You must do something like this in your Controller:

$user_id = 1;
$args = [$user_id];
$view = Drupal\views\Views::getView('my_view_id');
if (is_object($view)) {
  $view->setArguments($args);
  $view->setDisplay('page');
  $view->preExecute();
  $view->execute();
  return $view->buildRenderable('page', $args);
}
| improve this answer | |
  • Thank you for the advice. I haven't used the solution, but it's quite informative. – 863 Nov 8 '19 at 0:43
0

Jdrupal's answer totally makes sense, but as some custom modules in my site implements hook_query_alter, I used it again to keep it easy to understand for other developers. The code goes like this:

/**
 * Implements hook_views_query_alter().
 */
function MY_MODULE_views_query_alter(ViewExecutable $view, QueryPluginBase $query) {
  if ($view->id() !== 'MY_VIEW') {
    return;
  }
  $uid = \Drupal::currentUser()->id();
  $snipped = "node_field_data_node_field_revision.uid = $uid"; 
  $query->addWhereExpression(0, $snippet);
}
  • I took node_field_data_node_field_revision.uid from SQL query shown in the view preview (which needs to be enabled in /admin/structure/views/settings).
  • If you add a filter this way, the contextual filter needs to be deleted.
| improve this answer | |

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.