0

I would like to perform a string replace function on a field in views. What is the best way to access and change the value? A template will not work as the view is being output as JSON.

Is the best way hook_field_views_data_alter? If so I am having trouble implementing it in a module.

Or can I do this with a preprocess function? I tried the following. I can change the value but when I assign it back it is not output in the view.

function mytheme_preprocess_views_view_fields(&$variables) {
  $view = $variables['view'];
  $row = $variables['row'];
  $new_value = str_replace ( '.' , ',' , $row -> node__field_product_price_field_product_price_value );
  $row -> node__field_product_price_field_product_price_value = $new_value;
}

2 Answers 2

4

I don't know if this is the best way for you, but it works for me.

If view is being output as JSON, and you are using fields, then you can just edit field settings and use twig for this.

So in your field configuration, under Rewrite Results check Override the output of this field with custom text. Under Text you can put something like

{{ your_field_name|replace({".": ","}) }}

your field name can be found lower under Replacement patterns.

Of course, you are limited to twig with this method, but if it's just about string replacement I think it's fine.

1
  • 1
    It's not pretty but it is easy to implement and maintain. The cons are that it is not scalable or reusable.
    – Eyal
    Jun 14, 2016 at 22:07
0

You can implement your own FieldFormatter class (extending for example FormatterBase) and configure your view to use it.

Edit: although this approach works, it is not the Drupal way to do it. Thanks to @Eyal for pointing that out.

4
  • This will not work with views. The views module requires special plugins for fields and filters.
    – Eyal
    Jun 14, 2016 at 19:26
  • Of course that works. For example, the content view by core (views.view.content), displays the node title with the 'StringFormatter' (which also implements the 'ContainerFactoryPluginInterface')
    – Maouna
    Jun 14, 2016 at 19:38
  • See api.drupal.org/api/drupal/…
    – Eyal
    Jun 14, 2016 at 19:43
  • Views plugins must implement the \Drupal\views\Plugin\views\ViewsHandlerInterface and be declared using the @ViewsField / @ViewsFilter / ... annotations
    – Eyal
    Jun 14, 2016 at 19:52

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

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