0

Would it be possible to set the custom text field value in views? I have a simple calculation in custom text field. It gives me the correct calculation, but when I'm trying to aggregate the views to calculate the total sum from custom text field it returns 0 value.

I'm thinking that custom text field has no value in the first place and it's only output an HTML. Would it be possible to set custom text field value from the calculated output? Or is there any other way to achieve this without using the hook system?

Please note that I'm also attaching another view into custom text field which returns a total sum from another field.

2

Yes short Answer have a look at creating a custom twig extension:

the idea would be to pass the details required as an "exclude from display" field (or fields) to the custom global text field. Note excluded from display fields can be accessed in the "REPLACEMENT PATTERNS" section under view text.

then basically in the text field you would do something like:

{myCustomTwigFunctionToCalculate( add_REPLACEMENT_fields_here)} 
// or example ... 
{myCustomTwigFunctionToCalculate( entity_id, nid, uid)}


  namespace Drupal\YOURMODULE\Twig;


  class CustomTwigToCalculateTwigExtension extends \Twig_Extension {

  /**
   * {@inheritdoc}
   */
  public function getName() {
    return 'myCustomTwigFunctionToCalculate';
  }

  /**
   * {@inheritdoc}
   */
 public function getFunctions() {
    return [
      new \Twig_SimpleFunction('myCustomTwigFunctionToCalculate', [$this, 
      'myCustomTwigFunctionToCalculate'], [
      'is_safe' => ['html'],
    ]),
  ];
 }


 public function myCustomTwigFunctionToCalculated($param1 , $param2 ) : string {
 // Do the stuff you need to to calculate prams you pass. 

  $output = '';
  $output = $param1 + $param2 + 42;
  return (string) $output;
 }

}

you will also need a service file ... see below examples.

Links to custom twig extension for Drupal 8:

https://www.openaccess.fr/la-veille-du-web/create-twig-extension-drupal-8

https://medium.com/@thihathit/extending-custom-twig-extension-to-drupal-8-twig-extension-class-d4b99c2177ae

https://www.youtube.com/watch?v=9PeAfExNSDk

  • I think passing the field value should be enough. I'll have a look at it and check if it will work with aggregation. Thanks Taggart! – Madelyn Cruz Mar 19 at 1:41

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.