PHPackages                             jgrygierek/batch-entity-import-bundle - PHPackages - PHPackages  [Skip to content](#main-content)[PHPackages](/)[Directory](/)[Categories](/categories)[Trending](/trending)[Leaderboard](/leaderboard)[Changelog](/changelog)[Analyze](/analyze)[Collections](/collections)[Log in](/login)[Sign up](/register)

1. [Directory](/)
2. /
3. [PDF &amp; Document Generation](/categories/documents)
4. /
5. jgrygierek/batch-entity-import-bundle

ActiveSymfony-bundle[PDF &amp; Document Generation](/categories/documents)

jgrygierek/batch-entity-import-bundle
=====================================

Importing entities with preview and edit features for Symfony.

v3.9.0(4mo ago)101.1M↓42.5%6[1 issues](https://github.com/jgrygierek/BatchEntityImportBundle/issues)1MITPHPPHP &gt;=8.2.0CI failing

Since May 13Pushed 4mo ago1 watchersCompare

[ Source](https://github.com/jgrygierek/BatchEntityImportBundle)[ Packagist](https://packagist.org/packages/jgrygierek/batch-entity-import-bundle)[ RSS](/packages/jgrygierek-batch-entity-import-bundle/feed)WikiDiscussions master Synced 1mo ago

READMEChangelog (10)Dependencies (28)Versions (39)Used By (1)

BatchEntityImportBundle
=======================

[](#batchentityimportbundle)

[![Code Style](https://github.com/jgrygierek/BatchEntityImportBundle/workflows/Code%20Style/badge.svg)](https://github.com/jgrygierek/BatchEntityImportBundle/workflows/Code%20Style/badge.svg)[![Tests](https://github.com/jgrygierek/BatchEntityImportBundle/workflows/Tests/badge.svg)](https://github.com/jgrygierek/BatchEntityImportBundle/workflows/Tests/badge.svg)[![Code Coverage](https://camo.githubusercontent.com/d46cd011d4ee222187b93a8ff606502ead762b2306316908195c57101b382b3b/68747470733a2f2f696d672e736869656c64732e696f2f636f6465636f762f632f6769746875622f6a67727967696572656b2f4261746368456e74697479496d706f727442756e646c652f6d6173746572)](https://camo.githubusercontent.com/d46cd011d4ee222187b93a8ff606502ead762b2306316908195c57101b382b3b/68747470733a2f2f696d672e736869656c64732e696f2f636f6465636f762f632f6769746875622f6a67727967696572656b2f4261746368456e74697479496d706f727442756e646c652f6d6173746572)[![PHP Versions](https://camo.githubusercontent.com/1534d0b405b9bb0d789a6fc8b6b718b0700022832c625da411052bd8d783607e/68747470733a2f2f696d672e736869656c64732e696f2f62616467652f5048502d2533453d382e322d626c7565)](https://camo.githubusercontent.com/1534d0b405b9bb0d789a6fc8b6b718b0700022832c625da411052bd8d783607e/68747470733a2f2f696d672e736869656c64732e696f2f62616467652f5048502d2533453d382e322d626c7565)[![Symfony Versions](https://camo.githubusercontent.com/a0321aa9e31b82862f25cfdc8ca1ad054e658dde0ed1dfc337be65c66c082624/68747470733a2f2f696d672e736869656c64732e696f2f62616467652f53796d666f6e792d352e342d2d372e2a2d626c7565)](https://camo.githubusercontent.com/a0321aa9e31b82862f25cfdc8ca1ad054e658dde0ed1dfc337be65c66c082624/68747470733a2f2f696d672e736869656c64732e696f2f62616467652f53796d666f6e792d352e342d2d372e2a2d626c7565)[![SymfonyInsight](https://camo.githubusercontent.com/9fc43af125c23cc5feb43cd4eafcd406a3eee4787f7517b5e8b7e27e24fff89d/68747470733a2f2f696e73696768742e73796d666f6e792e636f6d2f70726f6a656374732f61643633353538652d333631322d343334662d613933642d3066633566636532646432302f6d696e692e737667)](https://insight.symfony.com/projects/ad63558e-3612-434f-a93d-0fc5fce2dd20)

Importing entities with preview and edit features for Symfony.

- Data can be **viewed and edited** before saving to database.
- Supports **inserting** new records and **updating** existing ones.
- Supported extensions: **CSV, XLS, XLSX, ODS**.
- Supports translations from **KnpLabs Translatable** extension.
- The code is divided into smaller methods that can be easily replaced if you want to change something.
- Columns names are required and should be added as header (first row).
- If column does not have name provided, will be removed from loaded data.

[![Select File](docs/select_file.png)](docs/select_file.png)[![Edit Matrix](docs/edit_matrix.png)](docs/edit_matrix.png)

Documentation
-------------

[](#documentation)

- [Installation](#installation)
- [Configuration class](#configuration-class)
    - [Basic configuration class](#basic-configuration-class)
    - [Fields definitions](#fields-definitions)
    - [Matrix validation](#matrix-validation)
    - [Passing services to configuration class](#passing-services-to-configuration-class)
    - [Show &amp; hide entity override column](#show--hide-entity-override-column)
    - [Set allowed file extensions](#set-allowed-file-extensions)
    - [Optimizing queries](#optimizing-queries)
- [Creating controller](#creating-controller)
- [Events](#events)
- [Translations](#translations)
- [Overriding templates](#overriding-templates)
    - [Global templates](#global-templates)
    - [Controller-specific templates](#controller-specific-templates)
    - [Main layout](#main-layout)
    - [Additional data](#additional-data)
- [Updating entities](#updating-entities)
- [Importing data to array field](#importing-data-to-array-field)
- [Full example of CSV file](#full-example-of-csv-file)

Installation
------------

[](#installation)

Install package via composer:

```
composer require jgrygierek/batch-entity-import-bundle

```

Add entry to `bundles.php` file:

```
JG\BatchEntityImportBundle\BatchEntityImportBundle::class => ['all' => true],

```

Configuration class
-------------------

[](#configuration-class)

To define how the import function should work, you need to create a configuration class.

### Basic configuration class

[](#basic-configuration-class)

In the simplest case it will contain only class of used entity.

```
namespace App\Model\ImportConfiguration;

use App\Entity\User;
use JG\BatchEntityImportBundle\Model\Configuration\AbstractImportConfiguration;

class UserImportConfiguration extends AbstractImportConfiguration
{
    public function getEntityClassName(): string
    {
        return User::class;
    }
}
```

Then register it as a service:

```
services:
  App\Model\ImportConfiguration\UserImportConfiguration: ~
```

### Fields definitions

[](#fields-definitions)

If you want to change types of rendered fields, instead of using default ones, you have to override method in your import configuration. If name of field contains spaces, you should use underscores instead.

To avoid errors during data import, you can add here validation rules.

```
use JG\BatchEntityImportBundle\Model\Form\FormFieldDefinition;
use Symfony\Component\Form\Extension\Core\Type\IntegerType;
use Symfony\Component\Form\Extension\Core\Type\TextareaType;
use Symfony\Component\Form\Extension\Core\Type\TextType;
use Symfony\Component\Validator\Constraints\Length;

public function getFieldsDefinitions(): array
{
    return [
        'age' => new FormFieldDefinition(
            IntegerType::class,
            [
                'attr' => [
                    'min' => 0,
                    'max' => 999,
                ],
            ]
        ),
        'name' => new FormFieldDefinition(TextType::class),
        'description' => new FormFieldDefinition(
            TextareaType::class,
            [
                'attr' => [
                    'rows' => 2,
                ],
                'constraints' => [new Length(['max' => 255])],
            ]
        ),
    ];
}
```

### Matrix validation

[](#matrix-validation)

This bundle provides two new validators.

1. **DatabaseEntityUnique** validator can be used to check if record data does not exist yet in database.
2. **MatrixRecordUnique** validator can be used to check duplication without checking database, just only matrix records values.

Names of fields should be the same as names of columns in your uploaded file. With one exception! If name contains spaces, you should use underscores instead.

```
use JG\BatchEntityImportBundle\Validator\Constraints\DatabaseEntityUnique;
use JG\BatchEntityImportBundle\Validator\Constraints\MatrixRecordUnique;

public function getMatrixConstraints(): array
{
    return [
        new MatrixRecordUnique(['fields' => ['field_name']]),
        new DatabaseEntityUnique(['entityClassName' => $this->getEntityClassName(), 'fields' => ['field_name']]),
    ];
}
```

### Passing services to configuration class

[](#passing-services-to-configuration-class)

If you want to pass some additional services to your configuration, just override constructor.

```
public function __construct(EntityManagerInterface $em, EventDispatcherInterface $eventDispatcher, TestService $service)
{
    parent::__construct($em, $eventDispatcher);

    $this->testService = $service;
}
```

### Show &amp; hide entity override column

[](#show--hide-entity-override-column)

If you want to hide/show an entity column that allows you to override entity `default: true`, you have to override this method in your import configuration.

```
public function allowOverrideEntity(): bool
{
    return true;
}
```

### Set allowed file extensions

[](#set-allowed-file-extensions)

By default, allowed file extensions are set to `'csv', 'xls', 'xlsx', 'ods'`. However, if you want to change it, you can override this method in your import configuration.

```
  public function getAllowedFileExtensions(): array
  {
      return ['csv', 'xls', 'xlsx', 'ods'];
  }
```

### Optimizing queries

[](#optimizing-queries)

If you use **KnpLabs Translatable** extension for your entity, probably you will notice increased number of queries, because of Lazy Loading.

To optimize this, you can use `getEntityTranslationRelationName()` method to pass the relation name to the translation.

```
public function getEntityTranslationRelationName(): ?string
{
    return 'translations';
}
```

Creating controller
-------------------

[](#creating-controller)

Create controller with some required code.

This is just an example, depending on your needs you can inject services in different ways.

To enable automatic passing configuration service to your controller, please use `ImportConfigurationAutoInjectInterface` and `ImportConfigurationAutoInjectTrait`.

```
namespace App\Controller;

use App\Model\ImportConfiguration\UserImportConfiguration;
use JG\BatchEntityImportBundle\Controller\ImportConfigurationAutoInjectInterface;
use JG\BatchEntityImportBundle\Controller\ImportConfigurationAutoInjectTrait;
use JG\BatchEntityImportBundle\Controller\ImportControllerTrait;
use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
use Symfony\Component\HttpFoundation\RedirectResponse;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\Routing\Annotation\Route;
use Symfony\Component\Validator\Validator\ValidatorInterface;
use Symfony\Contracts\Translation\TranslatorInterface;

class ImportController extends AbstractController implements ImportConfigurationAutoInjectInterface
{
    use ImportControllerTrait;
    use ImportConfigurationAutoInjectTrait;

    /**
     * @Route("/user/import", name="user_import")
     */
    public function import(Request $request, ValidatorInterface $validator): Response
    {
        return $this->doImport($request, $validator);
    }

    /**
     * @Route("/user/import/save", name="user_import_save")
     */
    public function importSave(Request $request, TranslatorInterface $translator): Response
    {
        return $this->doImportSave($request, $translator);
    }

    protected function redirectToImport(): RedirectResponse
    {
       return $this->redirectToRoute('user_import');
    }

    protected function getMatrixSaveActionUrl(): string
    {
       return $this->generateUrl('user_import_save');
    }

    protected function getImportConfigurationClassName(): string
    {
       return UserImportConfiguration::class;
    }
}
```

Events
------

[](#events)

### RecordImportedSuccessfullyEvent

[](#recordimportedsuccessfullyevent)

For each successfully processed record, event `RecordImportedSuccessfullyEvent` is dispatched. This event contains two fields:

- entity class name
- entity id

```
class RecordImportedSuccessfullyEvent
{
    public function __construct(public readonly string $class, public readonly string $id)
    {
    }
}
```

Translations
------------

[](#translations)

This bundle supports KnpLabs Translatable behavior.

To use this feature, every column with translatable values should be suffixed with locale, for example:

- `name:en`
- `description:pl`
- `title:ru`

If suffix will be added to non-translatable entity, field will be skipped.

If suffix will be added to translatable entity, but field will not be found in translation class, field will be skipped.

Overriding templates
--------------------

[](#overriding-templates)

#### Global templates

[](#global-templates)

You have two ways to override templates globally:

- **Configuration** - just change paths to templates in your configuration file. Values in this example are default ones and will be used if nothing will be change.

```
batch_entity_import:
    templates:
        select_file: '@BatchEntityImport/select_file.html.twig'
        edit_matrix: '@BatchEntityImport/edit_matrix.html.twig'
        layout: '@BatchEntityImport/layout.html.twig'
```

- **Bundle directory** - put your templates in this directory:

```
templates/bundles/BatchEntityImportBundle

```

#### Controller-specific templates

[](#controller-specific-templates)

If you have controller-specific templates, you can override them in controller:

```
protected function getSelectFileTemplateName(): string
{
    return 'your/path/to/select_file.html.twig';
}

protected function getMatrixEditTemplateName(): string
{
    return 'your/path/to/edit_matrix.html.twig';
}
```

#### Main layout

[](#main-layout)

Block name used in templates is `batch_entity_import_content`, so probably there will be need to override it a bit. You can create a new file with content similar to the given example. Then just use it instead of original layout file.

```
{% extends path/to/your/layout.html.twig %}

{% block your_real_block_name %}
    {% block batch_entity_import_content %}{% endblock %}
{% endblock %}
```

Then you just have to override it in bundle directory, or change a path to layout in your configuration.

#### Additional data

[](#additional-data)

If you want to add some specific data to the rendered view, just override these methods in your controller:

```
protected function prepareSelectFileView(FormInterface $form): Response
{
    return $this->prepareView(
        $this->getSelectFileTemplateName(),
        [
            'form' => $form->createView(),
        ]
    );
}

protected function prepareMatrixEditView(FormInterface $form, Matrix $matrix, bool $manualSubmit = false): Response
{
    if ($manualSubmit) {
        $this->manualSubmitMatrixForm($form, $matrix);
    }

    $configuration = $this->getImportConfiguration();

    return $this->prepareView(
        $this->getMatrixEditTemplateName(),
        [
            'header_info' => $matrix->getHeaderInfo($configuration->getEntityClassName()),
            'data' => $matrix->getRecords(),
            'form' => $form->createView(),
            'importConfiguration' => $configuration,
        ]
    );
}
```

Updating entities
-----------------

[](#updating-entities)

If you want to update your entities:

- Set `allowOverrideEntity` to `true` in your import configuration file.
- Then in your import file:
    - Add `entity_id` in header and:
        - Add entity ID to row
        - Leave it empty (if you want to set it manually or import it as new record)
    - Or if you don't want to add `entity_id` header, you can still manually set each entity to override.

#### CSV file

[](#csv-file)

```
entity_id,user_name
2,user_1
,user_2
10,user_3
```

Importing data to array field
-----------------------------

[](#importing-data-to-array-field)

If your entity has an array field, and you want to import data from CSV file to it, this is how you can do it.

- Default separator is set to `|`.
- Only one-dimensional arrays are allowed.
- Keys are not allowed.
- **IMPORTANT!** There are limitations:
    - There is no possibility to import array with one empty element, for example:
        - \[''\]
        - \[null\]
    - But arrays with at least 2 such elements are allowed:
        - \['', ''\]
        - \[null, null\]
        - \['', null\]
    - It is due of mapping CSV data to array:
        - Empty value in CSV is equal to `[]`
        - If we have default separator, `|` value in CSV is equal to `['', '']`

#### Entity

[](#entity)

- Allowed entity field types:
    - `json`
    - `array`
    - `simple_array`

```
namespace App\Entity;

use Doctrine\ORM\Mapping as ORM;

#[ORM\Entity]
class User
{
    #[ORM\Column(type: 'json']
    private array $roles = [];
}
```

#### Import configuration

[](#import-configuration)

- You have to add a field definition with a custom `ArrayTextType` type. If you skip this configuration, `TextType` will be used as default.
- You can set here your own separator.

```
use JG\BatchEntityImportBundle\Form\Type\ArrayTextType;
use JG\BatchEntityImportBundle\Model\Form\FormFieldDefinition;

public function getFieldsDefinitions(): array
{
    return [
        'roles' => new FormFieldDefinition(
            ArrayTextType::class,
            [
                'separator' => '&',
            ]
        ),
    ];
}
```

#### CSV file

[](#csv-file-1)

```
user_name,roles
user_1,USER&ADMIN&SUPER_ADMIN
user_2,USER
user_3,SUPER_ADMIN
```

Full example of CSV file
------------------------

[](#full-example-of-csv-file)

```
entity_id,user_name,age,email,roles,country:en,name:pl
1,user_1,21,user_1@test.com,USER&ADMIN&SUPER_ADMIN,Poland,Polska
3, user_2,34,user_2@test.com,USER,England,Anglia
,user_3,56,user_3@test.com,SUPER_ADMIN,Germany,Niemcy
```

###  Health Score

59

—

FairBetter than 99% of packages

Maintenance72

Regular maintenance activity

Popularity47

Moderate usage in the ecosystem

Community18

Small or concentrated contributor base

Maturity80

Battle-tested with a long release history

 Bus Factor1

Top contributor holds 90.7% of commits — single point of failure

How is this calculated?**Maintenance (25%)** — Last commit recency, latest release date, and issue-to-star ratio. Uses a 2-year decay window.

**Popularity (30%)** — Total and monthly downloads, GitHub stars, and forks. Logarithmic scaling prevents top-heavy scores.

**Community (15%)** — Contributors, dependents, forks, watchers, and maintainers. Measures real ecosystem engagement.

**Maturity (30%)** — Project age, version count, PHP version support, and release stability.

###  Release Activity

Cadence

Every ~57 days

Recently: every ~91 days

Total

37

Last Release

148d ago

Major Versions

v1.1.5 → v2.0.02021-09-16

v2.5.0 → v3.0.02022-05-29

v2.6.0 → v3.1.12023-11-24

PHP version history (4 changes)v1.0.0PHP ^7.4.0

v1.1.2PHP &gt;=7.4.0

v3.0.0PHP &gt;=8.1.0

v3.9.0PHP &gt;=8.2.0

### Community

Maintainers

![](https://www.gravatar.com/avatar/2d0beb45c27fa316a402deeb517b400e5dbb335564d9d1359f27cff82ff86fb3?d=identicon)[jgrygierek](/maintainers/jgrygierek)

---

Top Contributors

[![jgrygierek](https://avatars.githubusercontent.com/u/3065409?v=4)](https://github.com/jgrygierek "jgrygierek (185 commits)")[![michealmouner](https://avatars.githubusercontent.com/u/2089749?v=4)](https://github.com/michealmouner "michealmouner (14 commits)")[![a-afsharfarnia](https://avatars.githubusercontent.com/u/54709809?v=4)](https://github.com/a-afsharfarnia "a-afsharfarnia (3 commits)")[![rrr63](https://avatars.githubusercontent.com/u/46089601?v=4)](https://github.com/rrr63 "rrr63 (1 commits)")[![tomekknapczyk](https://avatars.githubusercontent.com/u/64355427?v=4)](https://github.com/tomekknapczyk "tomekknapczyk (1 commits)")

---

Tags

csv-importphpsymfonysymfony-bundlesymfonyexcelxlsxlsxcsvodsimportentitypreview

###  Code Quality

TestsPHPUnit

Static AnalysisPHPStan, Rector

Code StylePHP CS Fixer

Type Coverage Yes

### Embed Badge

![Health badge](/badges/jgrygierek-batch-entity-import-bundle/health.svg)

```
[![Health](https://phpackages.com/badges/jgrygierek-batch-entity-import-bundle/health.svg)](https://phpackages.com/packages/jgrygierek-batch-entity-import-bundle)
```

###  Alternatives

[sylius/sylius

E-Commerce platform for PHP, based on Symfony framework.

8.4k5.6M651](/packages/sylius-sylius)[easycorp/easyadmin-bundle

Admin generator for Symfony applications

4.3k16.7M310](/packages/easycorp-easyadmin-bundle)[prestashop/prestashop

PrestaShop is an Open Source e-commerce platform, committed to providing the best shopping cart experience for both merchants and customers.

9.0k15.4k](/packages/prestashop-prestashop)[ec-cube/ec-cube

EC-CUBE EC open platform.

78527.0k1](/packages/ec-cube-ec-cube)[sulu/sulu

Core framework that implements the functionality of the Sulu content management system

1.3k1.3M152](/packages/sulu-sulu)[contao/core-bundle

Contao Open Source CMS

1231.6M2.4k](/packages/contao-core-bundle)

PHPackages © 2026

[Directory](/)[Categories](/categories)[Trending](/trending)[Changelog](/changelog)[Analyze](/analyze)
