How to add a phpcr-odm ReferenceMany field to sonata admin? - symfony

In my document I have a field that I want to store the related nodes and I defined it like this:
/**
* #PHPCRODM\ReferenceMany(targetDocument="Symfony\Cmf\Bundle\SimpleCmsBundle\Doctrine\Phpcr\Page", strategy="hard")
*/
protected $related_guides;
I added the related nodes using the document manager and I can see them and created links in my twig file. The problem that I have is allowing the admin to add or delete the related nodes in the sonata admin.
When I used ORM I used 'sonata_type_collection' but it seems it doesn't work in ODM. I got this error:
INVALID MODE : s537a4d1c263c0_related_guides - type : sonata_type_collection - mapping : 8
sonata_type_model_list only works for ReferenceOne relations and for ReferenceMany I got this error:
The class 'Doctrine\ODM\PHPCR\ReferenceManyCollection' was not found in the chain configured namespaces Doctrine\ODM\PHPCR\Document, Sandbox\MainBundle\Document, Vectorworks\Bundle\CmsBundle\Document, Symfony\Component\Routing, Symfony\Cmf\Bundle\RoutingBundle\Model, Symfony\Cmf\Bundle\RoutingBundle\Doctrine\Phpcr, Symfony\Cmf\Bundle\MenuBundle\Model, Symfony\Cmf\Bundle\MenuBundle\Doctrine\Phpcr, Symfony\Cmf\Bundle\ContentBundle\Model, Symfony\Cmf\Bundle\ContentBundle\Doctrine\Phpcr, Symfony\Cmf\Bundle\BlockBundle\Model, Symfony\Cmf\Bundle\BlockBundle\Doctrine\Phpcr, Symfony\Cmf\Bundle\SimpleCmsBundle\Doctrine\Phpcr, Symfony\Cmf\Bundle\SeoBundle\Model, Symfony\Cmf\Bundle\SeoBundle\Doctrine\Phpcr, Symfony\Cmf\Bundle\MediaBundle\Doctrine\Phpcr
Is there any way to get this functionality out of Sonata Admin? BTW my fields is the type of Doctrine\ODM\PHPCR\ReferenceManyCollection to support the #ReferenceMany relation.

For ReferenceMany try using "phpcr_document":
$formPapper->add('related_guides', 'phpcr_document',
array(
'property' => 'title',
'class' => 'Acme\DemoBundle\Document\TargetClass',
'multiple' => true,
))
->end();

The above code seems to be a little old: for Symfony 3.3, use the following code:
use Doctrine\Bundle\PHPCRBundle\Form\Type\DocumentType;
...
$formPapper->add('related_guides', DocumentType::class,
array(
'choice_label' => 'title', // where TargetClass::getTitle()
'class' => 'Acme\DemoBundle\Document\TargetClass',
'multiple' => true,
))
->end();

Related

Options for VichFileType not taken into account in EasyAdmin 3 CRUD

I use Symfony 5.3, EasyAdmin 3.5, and Vich/Uploader-bundle 1.19
I want to manage uploads of PDF files into a EAsyAdmin CRUD controller.
Here is the configuration of my fields for this CRUD Controller
public function configureFields(string $pageName): iterable
{
return [
Field::new('document')->setFormType(VichFileType::class, [
'download_label' => 'Télécharger',
'allow_delete' => false,
])
];
}
But in my EasyAdmin Update Page, here is my result :
It seems that the options passed in my VichFileType are not used.
Further more, the default option for 'download_label' does not use french translation provided with Vich/Upload-bundle.
Do you have any idea ? Do You thinks it's a bug from my code of from VichUpload ?
Thanks for your help !
I found the solution, by using the command
Field::new('document')
->setFormType(VichFileType::class)
->setFormTypeOptions(
[
'download_label' => 'Télécharger',
'allow_delete' => false,
])
You should use the FormType, it's easier.
You put the imageFile in your form then your show the imageName in your twig.

How to configure a Translatable Entity in EasyAdmin?

I'm using Translatable and EasyAdmin in a Symfony 5 project and I have configured 2 languages.
The issue is I need to be able to edit the different languages of a record in EasyAdmin, I have checked the docs of Translatable, EasyAdmin and Symfony, There is very little information about how to integrate database translations into EasyAdmin.
Therefore, I'm a bit stuck in terms of code, I have tried configuring setTranslationParameters() inside the entity CRUD controller and changing some configuration in the DashboardController however, I don't think this is the right approach.
Any suggestions of how to solve this issue?
Thank you for your effort and time.
as of writing, this feature doesn't exist in EasyAdmin, please see the link to the answer to the issue on Github.
https://github.com/EasyCorp/EasyAdminBundle/issues/4982
However, a work around is possible with a different package:
remove doctrine-extensions/DoctrineExtensions and then install KnpLabs/DoctrineBehaviors
install a2lix/translation-form-bundle
Create a translation field:
<?php
declare(strict_types=1);
namespace App\Controller\Admin\Field;
use A2lix\TranslationFormBundle\Form\Type\TranslationsType;
use EasyCorp\Bundle\EasyAdminBundle\Contracts\Field\FieldInterface;
use EasyCorp\Bundle\EasyAdminBundle\Field\FieldTrait;
final class TranslationField implements FieldInterface
{
use FieldTrait;
public static function new(string $propertyName, ?string $label = null, array $fieldsConfig = []): self
{
return (new self())
->setProperty($propertyName)
->setLabel($label)
->setFormType(TranslationsType::class)
->setFormTypeOptions([
'default_locale' => 'cz',
'fields' => $fieldsConfig,
]);
}
}
Use the TranslationField inside your admin CRUD controller:
public function configureFields(string $pageName): iterable
{
return [
TextField::new('title', 'title')->hideOnForm(),
TranslationField::new('translations', 'translations', [
'title' => [
'field_type' => TextType::class,
'required' => true,
]
// add more translatable properties into the array
])->setRequired(true)
->hideOnIndex()
];
}

OroPlatform: add custom field on core Entity

I'm currently working on an OroPlatform project and I need to add a custom field on the BusinessUnit core entity.
I have read the Oro documentation section about the way to extend core entities : https://doc.oroinc.com/backend/entities/extend-entities/#id1
<?php
namespace MyBundle\Bundle\AppBundle\Migrations\Schema\v1_0;
use Doctrine\DBAL\Schema\Schema;
use Oro\Bundle\EntityExtendBundle\EntityConfig\ExtendScope;
use Oro\Bundle\MigrationBundle\Migration\Migration;
use Oro\Bundle\MigrationBundle\Migration\QueryBag;
class AddColumnsToBusinessUnit implements Migration
{
public function up(Schema $schema, QueryBag $queries)
{
$table = $schema->getTable('oro_business_unit');
$table->addColumn('siret', 'string', [
'oro_options' => [
'extend' => ['owner' => ExtendScope::OWNER_CUSTOM],
'entity' => ['label' => 'siret'],
],
]);
}
}
When I run the command symfony console oro:migration:load --force, it works and the migration is applied to my database.
Now, I want a required field. I have seen the instruction 'notnull' => true to setup a non nullable field on the database.
Everything works well, but my field hasn't any JavaScript validation on the organization/business_unit/create route. Any ideas ?
You can validate the new field by extending the validation metadata that is already defined for the core entity you are extending.
To do this, please follow the official Symfony documentation and use the YML format:
https://symfony.com/doc/4.4/validation.html#constraint-configuration
The constraint that you can use for the field is "not blank."
Here is an example:
# src/<YourBundlePath>/Resources/config/validation.yml
Oro\Bundle\OrganizationBundle\Entity\BusinessUnit:
properties:
siret:
- NotBlank: ~

Can I set the cardinality of an entity_reference to a config entity?

I programmatically created an entity_reference (to a config entity) field via hook_entity_base_field_info (see code below).
All works fine until I try to define its cardinality. As soon as I add this, I get fatal error because Drupal can't find the database table user__foo.
$fields['foo'] = BaseFieldDefinition::create('entity_reference')
->setLabel(t('Foo field'))
->setDescription(t('Foo bar field'))
->setSetting('target_type', 'my_config_entity')
->setSetting('handler', 'default')
// ->setCardinality(\Drupal\Core\Field\FieldStorageDefinitionInterface::CARDINALITY_UNLIMITED)
->setDisplayOptions('view', [
'label' => 'hidden',
'type' => 'entity_reference_label',
'weight' => 6,
])
->setDisplayOptions('form', [
'type' => 'options_buttons',
'weight' => 7,
]);
FYI, when doing a clean install with the cardinality uncommented, all works fine, so it's probably a matter of writing an update hook for existing sites to install storage for this new field (something done by drush entity-update earlier).

How do I create and instantiate a new custom field in hook_install() of the module that declares that custom field?

My module defines a custom field type with hook_field_info(). In hook_install() of this module, I am trying to create new fields and instances of this custom field type:
function my_module_install() {
if (!field_info_field('my_field')) {
$field = array(
'field_name' => 'my_field',
'type' => 'custom_field_type',
'cardinality' => 1
);
field_create_field($field);
}
}
The code crashes at field_create_field($field):
WD php: FieldException: Attempt to create a field of unknown type custom_field_type. in field_create_field() (line 110 of [error]
/path/to/modules/field/field.crud.inc).
Cannot modify header information - headers already sent by (output started at /path/to/drush/includes/output.inc:37) bootstrap.inc:1255 [warning]
FieldException: Attempt to create a field of unknown type <em class="placeholder">custom_field_type</em>. in field_create_field() (line 110 of /path/to/modules/field/field.crud.inc).
What's wrong?
You are trying to enable a module that defines field types and attempts to use those same field types in its hook_install(), before it's enabled. Drupal's field info cache is not rebuilt before hook_install() is run, so Drupal does not know about the field types in your module when you're trying to create your field.
To get around this, manually rebuild the field info cache by calling field_info_cache_clear() before field_create_field($field):
if (!field_info_field('my_field')) {
field_info_cache_clear();
$field = array(
'field_name' => 'my_field',
'type' => 'custom_field_type',
'cardinality' => 1
);
field_create_field($field);
}

Resources