• 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

How to clean a CSV file during a Product import¶

Foundations of connector creation have been covered in the previous chapter (cf How to create a new Connector). With the following hands-on practice, we will create our own specific connector.

To stay focused on the main concepts, we will implement the simplest connector possible by avoiding to use too many existing elements.

The use case is to clean the following CSV file when importing products:

1sku;name
2uselesspart-sku-1;my full name 1
3uselesspart-sku-2;my full name 2
4uselesspart-sku-3;my full name 3

Here, we want remove the prefix uselesspart- in the sku before running a classic import.

We assume that we’re using a standard edition with the icecat_demo_dev data set, sku and name already exist as real attributes of the PIM.

Note

The code inside this cookbook entry is available in the src directory, you can clone pim-docs (https://github.com/akeneo/pim-docs) and use a symlink to make the Acme bundle available in the src/. The same cookbook could be applied for XLSX Product Import

Create the Connector¶

Create a new bundle:

1<?php
2
3namespace Acme\Bundle\CsvCleanerConnectorBundle;
4
5use Symfony\Component\HttpKernel\Bundle\Bundle;
6
7class AcmeCsvCleanerConnectorBundle extends Bundle
8{
9}

Register the bundle in AppKernel:

1public function registerBundles()
2{
3    // ...
4        new Acme\Bundle\CsvCleanerConnectorBundle\AcmeCsvCleanerConnectorBundle(),
5    // ...
6}

Create the ArrayConverter¶

The purpose of the array converter is to transform the array provided by the reader to the standard array format, cf Understanding the Product Import

 1<?php
 2
 3namespace Acme\Bundle\CsvCleanerConnectorBundle\ArrayConverter\StandardToFlat;
 4
 5use Akeneo\Tool\Component\Connector\ArrayConverter\ArrayConverterInterface;
 6
 7class Product implements ArrayConverterInterface
 8{
 9    /** @var ArrayConverterInterface */
10    protected $productConverter;
11
12    /**
13     * @param ArrayConverterInterface $productConverter
14     */
15    public function __construct(ArrayConverterInterface $productConverter)
16    {
17        $this->productConverter = $productConverter;
18    }
19
20    public function convert(array $item, array $options = [])
21    {
22        // cleans the sku
23        $item['sku'] = str_replace('uselesspart-', '', $item['sku']);
24
25        $convertedItem = $this->productConverter->convert($item, $options);
26
27
28
29        return $convertedItem;
30    }
31}

Then we declare this new array converter service in array_converters.yml.

1parameters:
2    acme_csvcleanerconnector.array_converter.flat.product.class: 'Acme\Bundle\CsvCleanerConnectorBundle\ArrayConverter\StandardToFlat\Product'
3
4services:
5    acme_csvcleanerconnector.array_converter.flat.product:
6        class: '%acme_csvcleanerconnector.array_converter.flat.product.class%'
7        arguments:
8            - '@pim_connector.array_converter.flat_to_standard.product_delocalized'

Note

You can notice here that we use the Decorator Pattern by injecting the default array converter in our own class.

The big advantage of this practice is to decouple your custom code from the PIM code, for instance, if in the future, an extra dependency is injected in the constructor of the default array converter, your code will not be impacted.

Finally, we introduce the following extension to load the services files in configuration:

 1<?php
 2
 3namespace Acme\Bundle\CsvCleanerConnectorBundle\DependencyInjection;
 4
 5use Symfony\Component\HttpKernel\DependencyInjection\Extension;
 6use Symfony\Component\DependencyInjection\ContainerBuilder;
 7use Symfony\Component\DependencyInjection\Loader\YamlFileLoader;
 8use Symfony\Component\Config\FileLocator;
 9
10class AcmeCsvCleanerConnectorExtension extends Extension
11{
12    public function load(array $configs, ContainerBuilder $container)
13    {
14        $loader = new YamlFileLoader($container, new FileLocator(__DIR__.'/../Resources/config'));
15        $loader->load('array_converters.yml');
16        $loader->load('jobs.yml');
17        $loader->load('job_constraints.yml');
18        $loader->load('job_defaults.yml');
19        $loader->load('job_parameters.yml');
20        $loader->load('readers.yml');
21        $loader->load('steps.yml');
22    }
23}

Configure the Job¶

To be executed, a Job is launched with a JobParameters which contains runtime parameters. We also need a ConstraintCollectionProviderInterface which contains the form job constraints and the DefaultValuesProviderInterface which contains the default job values.

First we need to define the reader service with the new array converter:

1services:
2    acme_csvcleanerconnector.reader.file.csv_product:
3        class: '%pim_connector.reader.file.csv_product.class%'
4        arguments:
5            - '@pim_connector.reader.file.csv_iterator_factory'
6            - '@acme_csvcleanerconnector.array_converter.flat.product'
7            - '@pim_connector.reader.file.media_path_transformer'
8            - []

Then we need to create our custom step service definition to use our new reader:

 1services:
 2    acme_csvcleanerconnector.step.csv_product.import:
 3        class: '%pim_connector.step.item_step.class%'
 4        arguments:
 5            - 'import'
 6            - '@event_dispatcher'
 7            - '@akeneo_batch.job_repository'
 8            - '@acme_csvcleanerconnector.reader.file.csv_product'
 9            - '@pim_connector.processor.denormalization.product'
10            - '@pim_connector.writer.database.product'

Finally we need to create a new job configuration that uses our custom step:

 1parameters:
 2    acme_csvcleanerconnector.job_name.csv_product_import_cleaner: 'csv_product_import_cleaner'
 3
 4services:
 5    acme_csvcleanerconnector.job.csv_product_import_cleaner:
 6        class: '%pim_connector.job.simple_job.class%'
 7        arguments:
 8            - '%acme_csvcleanerconnector.job_name.csv_product_import_cleaner%'
 9            - '@event_dispatcher'
10            - '@akeneo_batch.job_repository'
11            -
12                - '@pim_connector.step.charset_validator'
13                - '@acme_csvcleanerconnector.step.csv_product.import'
14        tags:
15            - { name: akeneo_batch.job, connector: '%pim_connector.connector_name.csv%', type: '%pim_connector.job.import_type%' }

At this point, the job is usable in command line though it cannot be configured via the UI. We need to write a service providing the form type configuration for each parameter of our JobParameters instance:

 1services:
 2    acme_csvcleanerconnector.job_parameters.form_configuration_provider.product_csv_import_cleaner:
 3        class: '%pim_import_export.job_parameters.form_configuration_provider.product_csv_import.class%'
 4        arguments:
 5            - '@pim_import_export.job_parameters.form_configuration_provider.simple_csv_import'
 6            -
 7                - 'csv_product_import_cleaner'
 8            - '%pim_catalog.localization.decimal_separators%'
 9            - '%pim_catalog.localization.date_formats%'
10        tags:
11            - { name: pim_import_export.job_parameters.form_configuration_provider }
1services:
2    acme_csvcleanerconnector.job.job_parameters.constraint_collection_provider.product_csv_import:
3        class: '%pim_connector.job.job_parameters.constraint_collection_provider.product_csv_import.class%'
4        arguments:
5            - '@pim_connector.job.job_parameters.constraint_collection_provider.simple_csv_import'
6            -
7                - 'csv_product_import_cleaner'
8        tags:
9            - { name: akeneo_batch.job.job_parameters.constraint_collection_provider }
1services:
2    acme_csvcleanerconnector.job.job_parameters.default_values_provider.product_csv_import:
3        class: '%pim_connector.job.job_parameters.default_values_provider.product_csv_import.class%'
4        arguments:
5            - '@pim_connector.job.job_parameters.default_values_provider.simple_csv_import'
6            -
7                - 'csv_product_import_cleaner'
8        tags:
9            - { name: akeneo_batch.job.job_parameters.default_values_provider }

For further information you can check the How to create a new Connector

As for the jobs.yml, this service file job_parameters.yml must be loaded in our AcmeCsvCleanerConnectorExtension.

Translate Job and Step labels in the UI¶

Behind the scene, the service Akeneo\Platform\Bundle\ImportExportBundle\JobLabel\TranslatedLabelProvider provides translated Job and Step labels to be used in the UI.

This service uses following conventions: - for a job label, given a $jobName, “batch_jobs.$jobName.label” - for a step label, given a $jobName and a $stepName, “batch_jobs.$jobName.$stepName.label”

Create a file Resources/translations/messages.en.yml in our Bundle to translate label keys.

1batch_jobs:
2    csv_product_import_cleaner:
3        label: Product Import Cleaned Csv
4        import.label: Product import cleaned
5        validation.label:  File encoding validation

Use the new Connector¶

Now if you refresh the cache, the new export can be found under Extract > Import profiles > Create import profile.

You can run the job from the UI or you can use following command:

php bin/console akeneo:batch:publish-job-to-queue my_job_code --env=prod

Warning

One daemon or several daemon processes have to be started to execute the jobs. Please follow the documentation Setting up the job queue daemon if it’s not the case.


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