• v5.0
    • Versions
    • master

 

  • Install Akeneo PIM
    • Install Akeneo PIM for development with Docker
    • Install Akeneo PIM manually
      • System Requirements
      • System installation on Debian 10 (Buster)
      • System installation on Ubuntu 18.04 (Bionic Beaver)
      • System installation on Ubuntu 20.04 (Focal Fossa)
      • Installing Akeneo PIM Community Edition (CE)
      • Installing Akeneo PIM Enterprise Edition (EE) with the Archive
      • Setting up the job queue daemon
      • Setting up the Events API
    • How to customize the Dataset
    • How to Add Translation Packs
  • Upgrade Akeneo PIM projects
    • How to apply a patch?
      • How to apply a patch - Community Edition
      • How to apply a patch - Enterprise Edition - Flexibility Cloud offer
      • How to apply a patch - Enterprise Edition - On Premise offer
    • Where is the Changelog?
    • How to upgrade to a minor version?
    • How to upgrade to a major version?
      • Upgrade from 3.2 to 4.0
      • Upgrade from 4.0 to 5.0
  • Import and Export data
    • How import works
    • Understanding the Product Import
    • Understanding the Product Export
    • Formats
      • Localized labels
      • Scopable labels
      • Association types data structure
      • Attribute data structure
      • Category data structure
      • Family data structure
      • Family variant data structure
      • Group data structure
      • Options data structure
      • Product data structure
      • Product model data structure
    • Akeneo Connectors
    • How to Customize Import / Export
      • How to create a new Connector
      • How to import Products from a XML file
      • How to clean a CSV file during a Product import
      • How to automate imports/exports
  • Manipulate the Akeneo PIM data
    • How to Customize Mass Edit Operations
      • How to register a new bulk action
      • How to Register a New Mass Edit Action on Products
    • How to Manipulate Products
      • How to Query Products
      • How to Create Products
      • How to Update Products
      • How to Validate Products
      • How to Save Products
      • How to Remove Products
    • How to Manipulate Non-Product Objects
      • How to Query Non-Product Objects
      • How to Create Non-Product Objects
      • How to Update Non-Product Objects
      • How to Validate Non-Product Objects
      • How to Save Non-Product Objects
      • How to Remove Non-Product Objects
    • How to add a custom action rule
      • General information about rule format
      • How to add a custom action in the rule engine
    • How to Define Access Control List
    • How to Customize the Catalog Structure
      • How to Create a Reference Data
    • How To Customize Teamwork Assistant (Enterprise Edition)
      • Customize notifications
      • Add a calculation step
      • How to log calculation step
      • Remove projects impacted by a custom catalog update
    • How to store assets externally
    • How to Configure Measurement Limits
  • Maintain Akeneo PIM projects
    • First aid kit
    • Bug qualification
    • Common issues
    • Scalability Guide
      • Audit with 3 Representative Catalogs
      • More than 10k attributes?
      • More than 10k families?
      • More than 10k categories?
      • More than 500 attributes usable in the product grids?
      • More than 100k products to export?
      • More than 1GB of product media to export?
    • How to purge history
      • How to Purge jobs executions
      • How to adapt the version purger to your needs
  • Contribute to Akeneo PIM
    • How to report an issue?
    • How to translate the user interface?
    • How to enhance the documentation?
    • How to contribute to a Connector?
    • How to submit a patch to the PIM?
    • How to contribute to the frontend part of the application
    • How behavior tests are architectured in the PIM?
      • Establishing Decorator Pattern
      • Using Spin In Behat
  • Use SSO authentication locally
  • Reference Entities
    • Configure Entity Limits
    • Create a new Reference Entity Attribute type
    • Enrich Records with a new Reference Entity Attribute type
    • Add a Custom Property to Your Custom Attribute Type
    • Refresh records completeness
  • Troubleshooting guide
  • Technical overview
    • Product Information
    • Teamwork Assistant (Enterprise Edition)
      • Project creation
      • Project completeness
      • Project Completeness widget
      • Catalog update impact
      • Scalability guide
      • Users permission summary for Behat tests
    • Collaborative workflow
      • Simple workflow
      • Partial workflow
  • Technical architecture
    • Best Practices
      • Create a project
      • Create a reusable bundle
      • Code Conventions
      • Coding Standards
    • How to implement your business logic using the event system
    • Events
      • Storage events
      • Workflow events (Enterprise Edition only)
    • How to Localize your data
      • How to change the PIM locale
      • How to Use Localizers
      • How to use Presenters
    • How to Add a Notification
    • Performances Guide
      • Memory usage of rules execution (Enterprise Edition)
      • Memory leak fix in Rules Engine (ORM)
      • More than 100 WYSIWYG editors in a page
      • PHP7 and HHVM Compatibility?
      • Job product batch size
    • How to Use the Web REST API
    • Standard format
      • Products
      • Other entities
      • Usage
    • Application Technical Information
      • Application Technical Dependencies
      • Server side set up for hosting
      • System Requirements
      • Recommended configuration
      • Client side configuration and compatibilities
      • Operation processes
      • Flow Matrix
  • Akeneo Cloud Edition
    • Flexibility
      • Environment accesses
      • System Administration & Services Management
      • Periodic tasks & Crontab configuration
      • Composer settings
      • Queue Management & Workers
      • Disk Usage Management
    • Serenity
  • Akeneo Onboarder
    • Prerequisites
    • How to install the Onboarder bundle
    • Synchronization
    • How to update a minor version or to apply a patch
      • How to update the Onboarder bundle - Enterprise Edition - Flexibility Cloud offer
      • How to update the Onboarder bundle - Enterprise Edition - On Premise offer
    • How to upgrade to a major version
    • Troubleshooting
    • How to uninstall the Onboarder bundle
    • Environment variables
      • Using the DotEnv file
      • Using environment variables

Enrich Records with a new Reference Entity Attribute type¶

Note

Reference Entities feature is only available for the Enterprise Edition.

This cookbook will present how to enrich Records with a custom Reference Entity attribute type we just created in a previous step.

Enrich Records with the Attribute¶

In the previous tutorial, we’ve created a custom simple metric attribute. In this tutorial, we will be able to enrich this attribute directly in the records of the reference entity, for example here, the Surface attribute:

Enrich a Simple Metric value on a record

1) Your new Record value¶

To enrich a record, we will create a new Record Value for the brand new Attribute type. For example, we already have the TextData class for attribute type “Text”.

Let’s create our own SimpleMetricData that will handle the current data of the Record:

<?php

namespace Acme\CustomBundle\Record;

use Akeneo\ReferenceEntity\Domain\Model\Record\Value\ValueDataInterface;
use Webmozart\Assert\Assert;

class SimpleMetricData implements ValueDataInterface
{
    /** @var string */
    private $metricValue;

    private function __construct(string $metricValue)
    {
        $this->metricValue = $metricValue;
    }

    /**
     * @return string
     */
    public function normalize()
    {
        return $this->metricValue;
    }

    public static function createFromNormalize($normalizedData): ValueDataInterface
    {
        Assert::string($normalizedData, 'Normalized data should be a string');

        return new self($normalizedData);
    }

    public static function fromString(string $metricValue)
    {
        return new self($metricValue);
    }
}

2) Set a value for the new attribute¶

Let’s start by creating a command to represent the intent of updating the value:

<?php

namespace Acme\CustomBundle\Record;

use Acme\CustomBundle\Attribute\SimpleMetricAttribute;
use Akeneo\ReferenceEntity\Application\Record\EditRecord\CommandFactory\AbstractEditValueCommand;

class EditSimpleMetricValueCommand extends AbstractEditValueCommand
{
    /** @var string */
    public $newMetricValue;

    public function __construct(SimpleMetricAttribute $attribute, ?string $channel, ?string $locale, string $newMetricValue)
    {
        parent::__construct($attribute, $channel, $locale);

        $this->newMetricValue = $newMetricValue;
    }
}

And its factory to build the command:

<?php

namespace Acme\CustomBundle\Record;

use Acme\CustomBundle\Attribute\SimpleMetricAttribute;
use Akeneo\ReferenceEntity\Application\Record\EditRecord\CommandFactory\AbstractEditValueCommand;
use Akeneo\ReferenceEntity\Application\Record\EditRecord\CommandFactory\EditValueCommandFactoryInterface;
use Akeneo\ReferenceEntity\Domain\Model\Attribute\AbstractAttribute;

class EditSimpleMetricValueCommandFactory implements EditValueCommandFactoryInterface
{
    public function supports(AbstractAttribute $attribute, array $normalizedValue): bool
    {
         return
             $attribute instanceof SimpleMetricAttribute &&
            '' !== $normalizedValue['data'] &&
            is_string($normalizedValue['data']);
    }

    public function create(AbstractAttribute $attribute, array $normalizedValue): AbstractEditValueCommand
    {
        $command = new EditSimpleMetricValueCommand(
            $attribute,
            $normalizedValue['channel'],
            $normalizedValue['locale'],
            $normalizedValue['data']
        );

        return $command;
    }
}

Don’t forget to register your factory to be recognized by our registry:

acme.application.factory.record.edit_simple_metric_value_command_factory:
    class: Acme\CustomBundle\Record\EditSimpleMetricValueCommandFactory
    tags:
        - { name: akeneo_referenceentity.edit_record_value_command_factory }

Now that we have our command, we need a specific value updater that will be able to understand this command to update a simple metric value:

<?php

namespace Acme\CustomBundle\Record;

use Acme\CustomBundle\Record\EditSimpleMetricValueCommand;
use Acme\CustomBundle\Record\SimpleMetricData;
use Akeneo\ReferenceEntity\Application\Record\EditRecord\CommandFactory\AbstractEditValueCommand;
use Akeneo\ReferenceEntity\Application\Record\EditRecord\ValueUpdater\ValueUpdaterInterface;
use Akeneo\ReferenceEntity\Domain\Model\ChannelIdentifier;
use Akeneo\ReferenceEntity\Domain\Model\LocaleIdentifier;
use Akeneo\ReferenceEntity\Domain\Model\Record\Record;
use Akeneo\ReferenceEntity\Domain\Model\Record\Value\ChannelReference;
use Akeneo\ReferenceEntity\Domain\Model\Record\Value\LocaleReference;
use Akeneo\ReferenceEntity\Domain\Model\Record\Value\Value;

class SimpleMetricUpdater implements ValueUpdaterInterface
{
    public function supports(AbstractEditValueCommand $command): bool
    {
        return $command instanceof EditSimpleMetricValueCommand;
    }

    public function __invoke(Record $record, AbstractEditValueCommand $command): void
    {
        if (!$this->supports($command)) {
            throw new \RuntimeException('Impossible to update the value of the record with the given command.');
        }

        $attribute = $command->attribute->getIdentifier();
        $channelReference = (null !== $command->channel) ?
            ChannelReference::fromChannelIdentifier(ChannelIdentifier::fromCode($command->channel)) :
            ChannelReference::noReference();
        $localeReference = (null !== $command->locale) ?
            LocaleReference::fromLocaleIdentifier(LocaleIdentifier::fromCode($command->locale)) :
            LocaleReference::noReference();

        $metricValue = SimpleMetricData::createFromNormalize($command->metricValue);

        $value = Value::create($attribute, $channelReference, $localeReference, $metricValue);
        $record->setValue($value);
    }
}

We need to register this updater to be known by our registry:

acme.application.edit_record.record_value_updater.simple_metric_updater:
        class: Acme\CustomBundle\Record\SimpleMetricUpdater
        tags:
            - { name: akeneo_referenceentity.record_value_updater }

3) Retrieve our record value¶

Now that we can enrich our record with this new type of value, we need to create a dedicated hydrator, to hydrate our new record value from the DB:

<?php

namespace Acme\CustomBundle\Record;

use Acme\CustomBundle\Attribute\SimpleMetricAttribute;
use Acme\CustomBundle\Record\SimpleMetricData;
use Akeneo\ReferenceEntity\Domain\Model\Attribute\AbstractAttribute;
use Akeneo\ReferenceEntity\Domain\Model\Record\Value\ValueDataInterface;
use Akeneo\ReferenceEntity\Infrastructure\Persistence\Sql\Record\Hydrator\DataHydratorInterface;

class SimpleMetricDataHydrator implements DataHydratorInterface
{
    public function supports(AbstractAttribute $attribute): bool
    {
        return $attribute instanceof SimpleMetricAttribute;
    }

    public function hydrate($normalizedData): ValueDataInterface
    {
        return SimpleMetricData::createFromNormalize($normalizedData);
    }
}

And register it for the registry:

acme.infrastructure.persistence.record.hydrator.simple_metric_data:
    class: Acme\CustomBundle\Record\SimpleMetricDataHydrator
    tags:
        - { name: akeneo_referenceentity.data_hydrator }

Frontend Part of The New Record Value¶

To be able to enrich your records with this new attribute, we need to add some code in the frontend part.

To do so, you can put all needed code in one single file but you can (and are encouraged) to split it into multiple files if needed.

To keep this example simple, we will create everything in this file :

src/Acme/CustomBundle/Resources/public/reference-entity/record/simple-metric.tsx

Note

If you create a new Record Value, Akeneo will need three things to manage it in the frontend:

  • A model: a representation of your Record Value, its properties and overall behaviour

  • A view: as a React component to be able to render a user interface in the Record Form and dispatch events to the application

  • A cell: as a React component to be able to render a cell in the Record Grid

1) Model¶

The model of your custom Record Value will contain it’s properties and behaviours. To interface it with the rest of the PIM, your Record Value needs to extend the ValueData and provide a denormalizer.

This is the purpose of this section: provide a denormalizer capable of creating your custom Record Value extending the ValueData.

 1/**
 2 * ## Import section
 3 *
 4 * This is where your dependencies are to external modules using the standard import method (see https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/import)
 5 * The paths are absolute and the root is the public/bundles folder (at the root of your PIM project)
 6 */
 7import ValueData from 'akeneoreferenceentity/domain/model/record/data';
 8
 9class InvalidTypeError extends Error {}
10
11/**
12 * Here we are implementing our custom Record Value model.
13 */
14export type NormalizedSimpleMetricData = string | null;
15class SimpleMetricData extends ValueData {
16  private constructor(private simpleMetricData: string) {
17    super();
18
19    if ('string' !== typeof simpleMetricData) {
20      throw new InvalidTypeError('SimpleMetricData expects a string as parameter to be created');
21    }
22
23    Object.freeze(this);
24  }
25
26  /**
27   * Here, we denormalize our record value
28   */
29  public static createFromNormalized(simpleMetricData: NormalizedSimpleMetricData): SimpleMetricData {
30    return new SimpleMetricData(null === simpleMetricData ? '' : simpleMetricData);
31  }
32
33  /**
34   * Check the emptiness
35   */
36  public isEmpty(): boolean {
37    return '' === this.simpleMetricData;
38  }
39
40  /**
41  * Check if the value is equal to the simple metric data
42  */
43  public equals(data: ValueData): boolean {
44    return data instanceof SimpleMetricData && this.simpleMetricData === data.simpleMetricData;
45  }
46
47  /**
48   * The only method to implement here: the normalize method. Here you need to provide a serializable object (see https://developer.mozilla.org/en-US/docs/Glossary/Serialization)
49   */
50  public normalize(): string {
51    return this.simpleMetricData;
52  }
53}
54
55/**
56 * The only required part of the file: exporting a denormalize method returning a simple metric Record Value.
57 */
58export const denormalize = SimpleMetricData.createFromNormalized;

2) View¶

Now that we have our custom Record Value model we can now create the React component to be able to render a user interface in the Record Form and dispatch events to the application (https://reactjs.org/docs/react-component.html).

 1import * as React from 'react';
 2import Value from 'akeneoreferenceentity/domain/model/record/value';
 3import {ConcreteSimpleMetricAttribute} from 'custom/reference-entity/attribute/simple_metric.tsx';
 4import Key from 'akeneoreferenceentity/tools/key';
 5
 6/**
 7 * Here we define the React Component as a function with the following props :
 8 *    - the custom Record Value
 9 *    - the callback function to update the Record Value
10 *    - the callback for the submit
11 *    - the right to edit the Record Value
12 *
13 * It returns the JSX View to display the field of the custom Record Value.
14 */
15const View = ({
16  value,
17  onChange,
18  onSubmit,
19  canEditData,
20}: {
21  value: Value;
22  onChange: (value: Value) => void;
23  onSubmit: () => void;
24  canEditData: boolean;
25}) => {
26  if (!(value.data instanceof SimpleMetricData && value.attribute instanceof ConcreteSimpleMetricAttribute)) {
27    return null;
28  }
29
30  const onValueChange = (text: string) => {
31    const newData = denormalize(text);
32    if (newData.equals(value.data)) {
33      return;
34    }
35
36    const newValue = value.setData(newData);
37
38    onChange(newValue);
39  };
40
41  return (
42    <React.Fragment>
43      <input
44        id={`pim_reference_entity.record.enrich.${value.attribute.getCode().stringValue()}`}
45        autoComplete="off"
46        className={`AknTextField AknTextField--narrow AknTextField--light
47          ${value.attribute.valuePerLocale ? 'AknTextField--localizable' : ''}
48          ${!canEditData ? 'AknTextField--disabled' : ''}`}
49        value={value.data.normalize()}
50        onChange={(event: React.ChangeEvent<HTMLInputElement>) => {
51          onValueChange(event.currentTarget.value);
52        }}
53        onKeyDown={(event: React.KeyboardEvent<HTMLInputElement>) => {
54          if (Key.Enter === event.key) onSubmit();
55        }}
56        disabled={!canEditData}
57        readOnly={!canEditData}
58      />
59      <span>{value.attribute.unit.normalize()}</span>
60    </React.Fragment>
61  );
62};
63
64/**
65 * The only required part of the file: exporting the custom Record Value view.
66 */
67export const view = View;

3) Cell¶

The last part we need to do is to create the React component to be able to render a cell in the Record Grid.

 1import {NormalizedValue} from 'akeneoreferenceentity/domain/model/record/value';
 2import {CellView} from 'akeneoreferenceentity/application/configuration/value';
 3import {denormalize as denormalizeAttribute} from 'custom/reference-entity/attribute/simple_metric';
 4import {NormalizedSimpleMetricAttribute} from 'custom/reference-entity/attribute/simple_metric';
 5import {Column} from 'akeneoreferenceentity/application/reducer/grid';
 6
 7const memo = (React as any).memo;
 8
 9/**
10 * Here we define the React Component as a function with the following props :
11 *    - the custom Record Value
12 *
13 * It returns the JSX View to display the cell of your custom Record Value in the grid.
14 */
15const SimpleMetricCellView: CellView = memo(({column, value}: {column: Column, value: NormalizedValue}) => {
16  const simpleMetricData = denormalize(value.data);
17  const simpleMetricAttribute = denormalizeAttribute(column.attribute as NormalizedSimpleMetricAttribute);
18
19  return (
20    <div className="AknGrid-bodyCellContainer" title={simpleMetricData.normalize()}>
21      {simpleMetricData.normalize()}
22      <span>{simpleMetricAttribute.unit.normalize()}</span>
23    </div>
24  );
25});
26
27/**
28 * The only required part of the file: exporting the custom Record Value cell.
29 */
30export const cell = SimpleMetricCellView;

4) Register our custom Record Value¶

To be able to have everything working, we need to register our custom Record Value in the src/Acme/CustomBundle/Resources/config/requirejs.yml :

config:
    config:
        akeneoreferenceentity/application/configuration/value:
            simple_metric:
                denormalize: '@custom/reference-entity/record/simple-metric.tsx'
                view: '@custom/reference-entity/record/simple-metric.tsx'
                cell: '@custom/reference-entity/record/simple-metric.tsx'

API Part of The New Record Value¶

1) Json schema validator of a simple metric value when creating or updating a record¶

In order to validate the format of the value when creating or editing a record, we have to create a Json Schema validator for the simple metric value.

<?php

declare(strict_types=1);

namespace Acme\CustomBundle\Record\JsonSchema;

use Acme\CustomBundle\Attribute\SimpleMetricAttribute;
use Akeneo\ReferenceEntity\Infrastructure\Connector\Api\Record\JsonSchema\RecordValueValidatorInterface;
use JsonSchema\Validator;

class SimpleMetricTypeValidator implements RecordValueValidatorInterface
{
    /**
     * {@inheritdoc}
     */
    public function validate(array $normalizedRecord): array
    {
        $record = Validator::arrayToObjectRecursive($normalizedRecord);
        $validator = new Validator();
        $validator->validate($record, $this->getJsonSchema());

        return $validator->getErrors();
    }

    public function forAttributeType(): string
    {
        return SimpleMetricAttribute::class;
    }

    private function getJsonSchema(): array
    {
        return [
            'type' => 'object',
            'properties' => [
                'values' => [
                    'type' => 'object',
                    'patternProperties' => [
                        '.+' => [
                            'type'  => 'array',
                            'items' => [
                                'type' => 'object',
                                'properties' => [
                                    'locale' => [
                                        'type' => ['string', 'null'],
                                    ],
                                    'channel' => [
                                        'type' => ['string', 'null'],
                                    ],
                                    'data' => [
                                        'type' => ['string', 'null'],
                                    ],
                                ],
                                'required' => ['locale', 'channel', 'data'],
                                'additionalProperties' => false,
                            ],
                        ],
                    ],
                ],
            ],
        ];
    }
}

And to register it:

# src/Acme/CustomBundle/Resources/config/services.yml

services:
    acme.infrastructure.connector.api.record_value_simple_metric_type_validator:
        class: Acme\CustomBundle\Record\JsonSchema\SimpleMetricTypeValidator
        tags:
            - { name: akeneo_referenceentity.connector.api.record_value_validator }

Found a typo or a hole in the documentation and feel like contributing?
Join us on Github!