1

I have a custom node type "product" which has a custom Decimal type field "field_price".

I would like to create a simple module in Drupal 8 to set this value to 10.75 every time I create or update a node.

edit

I have now restructured the module as follows. These are the files / folder structure I have (excluding the .info.yml) :

Module folder: /modules/updateprices

Routing.yml: /modules/updateprices/update_prices.routing.yml

Routing.yml code:
update_prices:
    path: /updateprices
    defaults:
        _controller: 'Drupal\updateprices\Controller\UpdatePricesController::update_prices_node_presave'
    requirements:
        _permission: 'access content'

Controller code: /modules/updateprices/src/Controller/UpdatePricesController.php

<?php
namespace Drupal\updateprices\Controller;
use Drupal\Core\Entity\EntityInterface;

class UpdatePricesController  {
        function update_prices_node_presave(EntityInterface $entity) {

          $entity_type = 'node';
          $bundles = ['product'];

          $fld_price = 'field_price';
          if ($entity->getEntityTypeId() != $entity_type || !in_array($entity->bundle(), $bundles)) {
            return;
          }
             $entity->{$fld_price}->setValue(10.75);
        } 
}

I am now getting an error:

ReflectionException: Class Drupal\updateprices\Controller\UpdatePricesController does not exist in ReflectionMethod->__construct() (line 123 of /home/website.com/core/lib/Drupal/Core/Entity/EntityResolverManager.php).

1

Hooks, in a module, only work inside the .module file.

You don't need a controller nor a routing file here, these are used for creating pages.

/modules/updateprices/updateprices.module

<?php

use Drupal\Core\Entity\EntityInterface;

function update_prices_node_presave(EntityInterface $entity) {

  $entity_type = 'node';
  $bundles = ['product'];

  $fld_price = 'field_price';
  if ($entity->getEntityTypeId() != $entity_type || !in_array($entity->bundle(), $bundles)) {
    return;
  }
  $entity->{$fld_price}->setValue(10.75);

} 
  • Thanks for your help. I did all of the above. I have restructured the question to show the state of the module now. Still getting error. – ibexy Jun 30 '18 at 16:02
  • @ibexy updated my answer based on your update. – No Sssweat Jun 30 '18 at 20:05

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.