2

In a custom module I have defined a display suite field like so:

namespace Drupal\custom_dsfields\Plugin\DsField;
use Drupal\ds\Plugin\DsField\DsFieldBase;
//Views
/**
 * Plugin that renders the field.
 *
 * @DsField(
 *   id = "total_hours",
 *   title = @Translation("Total hours"),
 *   entity_type = "node",
 *   provider = "custom_dsfields",
 *   
 * )
 */
class MyField extends DsFieldBase
{
    /**
    * {@inheritdoc}
    */
    public function build(){

        $node = \Drupal::routeMatch()->getParameter('node');
        $entities = [];
        $hours = [];
        foreach ($node->field_hours as $key => $value) {
            array_push($entities, $value->target_id);
        }
        $entities = entity_load_multiple('user_entities', $entities, $reset = FALSE);
        foreach ($entities as $key => $value) {
            array_push($hours, $value->field_hours->value);
        }
        $hours_sum = array_sum($hours);

        return array(
            '#markup' => '<strong>Total hours for this day ' . $hours_sum . '</strong>'
            // '#theme' => 'item_list',
            // '#items' => $hours_sum
            );
        }
    }

In the default display this works perfect. (open to improvements But when I use a view, and display the teaser display with this field in it then the field is not working. Why is this?

Some things I am questioning...

  • Am I loading the node in the correct way as I am not entirely sure what routeMatch() is doing.
  • Should I be doing this in a view template (hope not)

Thanks DSE!

1 Answer 1

2

I found a better way to access the node so this will work anywhere.

$this->entity();

Inside the current class it will load the entity, in this case, the node.

Happy drupaling!

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.