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


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
    It's not pretty but it is easy to implement and maintain. The cons are that it is not scalable or reusable.
    – Eyal
    Commented Jun 14, 2016 at 22:07

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.

  • This will not work with views. The views module requires special plugins for fields and filters.
    – Eyal
    Commented 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
    Commented Jun 14, 2016 at 19:38
  • See api.drupal.org/api/drupal/…
    – Eyal
    Commented 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
    Commented Jun 14, 2016 at 19:52

Your Answer

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

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