Create a view to display a field that is specified by parameter

I need to create a view in Drupal 10 that shows all nodes of a set content type that has a given field not empty.
But I want to pass the field name/id as a parameter.

So the view will return all nodes with field_1 not empty when I pass ‘field_1’ as parameter.
And it will return all nodes with field_2 not empty when I pass ‘field_2’ as a parameter.

My initial feeling is that it’s not possible but I know there are magicians out there…

Thanks!

Creating a Dynamic View in Drupal 10 Based on Field Parameter

Understanding the Requirement:

You want to create a view that dynamically filters nodes based on a specified field. The field name should be passed as a parameter to the view.

Solution:

  1. Create a View:
  • Create a new view and set the content type to the desired one.
  • Add a filter criterion for the field you want to use (e.g., “Content: Field_1”).
  • Important: Leave the filter value empty.
  1. Add a Contextual Filter:
  • Add a contextual filter.
  • Choose the same field you used in the filter criterion.
  • Set the “When this filter is not available” option to “Provide a default value”.
  • Set the default value to the field name (e.g., “field_1”).
  1. Configure the View:
  • Configure the view as needed (e.g., sort criteria, fields to display).

Using the View:

  • When you access the view’s path, it will display nodes where the field specified in the default value (e.g., “field_1”) is not empty.
  • To filter by a different field, append the field name to the view’s path. For example, if the view’s path is /my-view , you can filter by “field_2” using /my-view/field_2 .

Example:

If your view’s path is /my-view and the default filter field is “field_1”, the following URLs will filter the view:

  • /my-view : Displays nodes where “field_1” is not empty.
  • /my-view/field_2 : Displays nodes where “field_2” is not empty.

Additional Considerations:

  • Contextual Filter Configuration: You can further customize the contextual filter’s behavior (e.g., allow multiple values, require a value) based on your specific needs.
  • Dynamic Views Module: Consider using the Dynamic Views module for more complex dynamic filtering scenarios.
  • Custom Code: If you require more advanced logic or customization, you can explore using custom code within the view’s template or controller.

By following these steps, you can create a dynamic view in Drupal 10 that filters nodes based on a specified field parameter.