I'm trying to send an EntityManager object to my custom validator. For that, I created a service and defined the entity manager as an argument.
The problem is that the argument isn't sent to the validator, it fires an error in the __construct() function indicating that no arguments have been passed.
This is the definition of my service:
dinamic.shop.validator.deliverydate:
class: Dinamic\ShopBundle\Validator\Constraints\DeliveryDateValidator
arguments:
- #doctrine.orm.entity_manager
tags:
- { name: validator.constraint_validator, alias: deliverydate }
Here is the validateBy() method of my Constraint:
class DeliveryDate extends Constraints
{
...
public function validateBy()
{
return 'deliverydate';
}
}
Here is my ConstraintValidator:
Finally, this is how I set the constraint on the field. The field is not mapped to any entity:
->add('deliveryday', 'date', array(
'label' => 'Día de entrega',
'widget' => 'single_text',
'format' => 'dd/MM/yyyy',
'constraints' => array(
new NotBlank(),
new DeliveryDate($deliveryDateOptions),
),
)
)
I think that my error is in the FormType class, where I set the constraint on the field, but I can't find any examples of non-mapped fields.
I'm using Symfony2.3, any help will be appreciated, thanks a lot.
[EDIT]
I've used the command "sudo php app/console container:debug | grep validator" and the service I've created appears on the results
dinamic.shop.validator.deliverydate container Dinamic\ShopBundle\Validator\Constraints\DeliveryDateValidator
It's very likely one of those syntax issues!
The syntax can be this:
dinamic.shop.validator.deliverydate:
class: Dinamic\ShopBundle\Validator\Constraints\DeliveryDateValidator
arguments: [#doctrine.orm.entity_manager]
tags:
- { name: validator.constraint_validator, alias: deliverydate }
or this:
dinamic.shop.validator.deliverydate:
class: Dinamic\ShopBundle\Validator\Constraints\DeliveryDateValidator
arguments:
entityManager: "#doctrine.orm.entity_manager"
tags:
- { name: validator.constraint_validator, alias: deliverydate }
Note: To check if the service you're passing exists:
php app/console container:debug | grep doctrine
Will give you:
....
doctrine.orm.entity_manager n/a alias for doctrine.orm.default_entity_manager
....
I found the error. The problem was the function 'validateBy', it should have been validatedBy()
So the only change I needed to do was to change said function.
Thank you for the help #Patt
Related
There is A LOT of similar quesions, some of them have validated answers, but here I am and none of them worked.
My use case is pretty simple:
My users App\Client\common\Entities\User belong to a customer App\Client\common\Entities\Customer.
App\Client\common\Entities\User also inherits FOS\UserBundle\Model\User which contains the holy property "email"
I want to serialize all my customers AND their users (including their mail). Jms works pretty well except i can not access properties from the FOS\UserBundle\Model\User class.
following this answer here is what I have now.
jms_serializer.yml
jms_serializer:
#blablablaa....
metadata:
auto_detection: true
directories:
App:
namespace_prefix: 'App\Client'
path: '%kernel.project_dir%/serializer'
FOSUB:
namespace_prefix: 'FOS\UserBundle'
path: '%kernel.project_dir%/serializer'
serializer/App.Client.common.Entities.User.yml :
App\Client\common\Entities\User:
exclusion_policy: ALL
properties:
surname:
expose: true
exclude: false
groups: [export]
serializer/Model.User.yml:
FOS\UserBundle\Model\User:
exclusion_policy: ALL
properties:
email:
expose: true
exclude: false
groups: [export]
src/Command/DeploySyncUsersCommand.php:
protected function execute(InputInterface $input, OutputInterface $output)
{
$users = $this->customerRepository->findAll(); //this is an array of Customer
$context = new SerializationContext();
$context->setGroups(['export']);
$serializer = SerializerBuilder::create()->build();
$json = $serializer->serialize($users, 'json', $context);
// do something with json
}
Everything works fine except the json does NOT contain email or any FOSUser\User data.
Also something interesting is that I can write anything (even invalid yml) in the App.Client.common.Entities.User.yml and Model.User.yml files, I'm able to clear the cache with no errors. I have errors when I write invalid yml in jms_serializer.yml
Ok I've been able to solve this using dependency injection instead of building the serializer
/**
* #var SerializerInterface
*/
private SerializerInterface $serializer;
/**
* #var string
*/
private string $reportAnalysisUrl;
public function __construct(SerializerInterface $serialzer, $reportAnalysis)
{
$this->serializer = $serialzer;
parent::__construct();
}
protected function execute(InputInterface $input, OutputInterface $output)
{
$users = $this->customerRepository->findAll();
$context = new SerializationContext();
$context->setGroups(['export']);
$json = $this->serializer->serialize($users, 'json', $context);
//do something with json
}
so now my yml files aren't ignored anymore
This is part of my code:
$form = new Form(new Shop());
$form->tab('terminal', function (Form $form) use ($id) {
$form->hasMany('shopterminal', '', function (Form\NestedForm $form) {
$form->text('terminal_num', 'terminal number')->required();
$form->select('poz_type', 'POS type')->options(['static' => 'one', 'dynamic' => 'two'])->required();
$form->select('psp_id', 'POZ name')->options(Psp::pluck('name', 'id'))->required();
$form->text('sheba', 'sheba number');
$form->text('account_num', 'account number')->required();
$form->select('bank_id', 'bank name')->options(Bank::pluck('name', 'id'))->required();
dd($form);
});
Here is the result of dd($form):
I need to get the value of terminal_image item (which is 15841949062134.png). Any idea how can I get it?
Noted that, neither of below syntax works:
$form->get('terminal_image')
$form->select('terminal_image')
$form->terminal_image
$form()->terminal_image
$form->relation->terminal_image
For your specific example:
$form->form->model->shopterminal[0]->terminal_image
you can use :
$form->form->model->relations['shopterminal']->items[0]->attributes['terminal_image']
I'm having problems with validator on Route.resource(). The validator is not been applied and when I run the command "adonis route:list" the av:TrainingPlan and Workout validators are not being listed. You can see that my other validators are working on single endpoint verb like "Route.post" on /users, /sessions/ and /passwords. On app.js under start folder I checked that the register was made too and all validator was generated by adonis cli.
My routes file was made based on documentation:
Route.group(() => {
Route.post('files', 'FileController.store')
Route
.resource('/training-plans', 'TrainingPlanController')
.apiOnly()
.validator(new Map([
[['training-plans.store'], ['TrainingPlan']]
]))
Route
.resource('/workouts', 'WorkoutController')
.apiOnly()
.validator(new Map([
[['workouts.store'], ['Workout']]
]))
}).middleware(['auth'])
TrainingPlan Validator:
'use strict'
class TrainingPlan {
get validateAll () {
return true
}
get rules () {
return {
title: 'required',
description: 'required',
start_date: `date|before:${new Date()}`,
end_date: `date|before:${new Date()}`
}
}
}
module.exports = TrainingPlan
What I'm missing out?
adonis route:list command result
The problem was resolved removing / before /workouts and /training-plans route.
I did not tested putting / before workouts.store and training-plans.store inside Map validator.
I am using doctrine2 with oracle. There are several schemas schema1 and schema2. When I create a form with the following content
// ....
public function buildForm(FormBuilderInterface $builder, array $options)
{
// ....
$builder
->add('userPartner', 'entity', array(
'class' => 'SoftclubTopbyBundle:Party',
'property' => 'legalName',
'placeholder' => '',
'multiple' => true,
))
;
// ....
}
//...
the symfony throws me an exception:
MappingException in MappingException.php line 37:
The class 'Softclub\TopbyBundle\Entity\Nsi\NsiChainStore' was not found in
the chain configured namespaces Softclub\TopbyBundle\Entity\Topby
I have the following setting in the config.yml
entity_managers:
default:
connection: default
mappings:
SoftclubTopbyBundle: { type: yml, dir: Resources/config/doctrine/topby, prefix: Softclub\TopbyBundle\Entity\Topby }
nsi:
connection: nsi
mappings:
SoftclubTopbyBundle: { type: yml, dir: Resources/config/doctrine/nsi, prefix: Softclub\TopbyBundle\Entity\Nsi }
and also the following relationship between the two entities
Softclub\TopbyBundle\Entity\Topby\Party:
manyToOne:
chainStore:
targetEntity: Softclub\TopbyBundle\Entity\Nsi\NsiChainStore
cascade: { }
mappedBy: null
inversedBy: null
joinColumns:
CHAIN_STORE_ID:
referencedColumnName: ID
orphanRemoval: false
what can I do wrong?
Thank you all for the answers. As Matteo said, the entities were placed in a separate bundle. The problem was solved as follows
default:
connection: default
mappings:
SoftclubTopbyBundle: ~
SoftclubNsiBundle: ~
# for generate entities
topby:
connection: default
mappings:
SoftclubTopbyBundle: ~
nsi:
connection: nsi
mappings:
SoftclubNsiBundle: ~
You can not make doctrine relations over different connections. You can use event listener for that purpose.
For instance, one entity (say Note) has some property which is reference to another entity (say User) belonging to another entity manager (connection). The Note entity persists User's ID as foreign key.
Event listener is used to instantiate User object by using it's ID whenever the Note object is loaded (postLoad event).
http://symfony.com/doc/current/cookbook/doctrine/event_listeners_subscribers.html
Doctrine events:
http://doctrine-orm.readthedocs.org/en/latest/reference/events.html#lifecycle-events
Regarding the form, put option entity manager with 'nsi' if 'userPartner' is mapped to that connection.
'em'=>'nsi'
Have not worked with Oracle, hope this helps.
I installed a email validator for a newsletter form in Symfony2. Locally everything works fine, but if I upload the whole folder to my webhosting i get the following error message:
Fatal error: Class 'Symfony\Component\Validator\Constraints\email' not found in /home/donacico/public_html/spendu/donaci14/vendor/symfony/symfony/src/Symfony/Component/Validator/Mapping/Loader/AbstractLoader.php on line 64
My validation yml looks like this:
# src/Dbe/DonaciBundle/Resources/config/validation.yml
Dbe\DonaciBundle\Entity\Newsletter:
properties:
email:
- email:
message: The email "{{ value }}" is not a valid email.
checkMX: true
Dbe\DonaciBundle\Entity\Contact:
properties:
email:
- email:
message: The email "{{ value }}" is not a valid email.
checkMX: true
And here is the action of the create controller:
/**
* Creates a new Newsletter entity.
*
*/
public function createAction(Request $request) {
$entity = new Newsletter();
$form = $this -> createCreateForm($entity);
$form -> handleRequest($request);
if ($form -> isValid()) {
$em = $this -> getDoctrine() -> getManager();
$em -> persist($entity);
$em -> flush();
$this -> get('session') -> getFlashBag() -> add('newsletterSubscribed', 'Thank you for subscribing!');
}
return $this -> render('DbeDonaciBundle:UnderConstruction:index.html.twig', array('entity' => $entity, 'form' => $form -> createView(), ));
}
Also in the config.yml file I have validation enabled:
framework:
validation: { enable_annotations: true }
Any idea what could cause this error?
If you work on a linux system its case sensitive.
'Symfony\Component\Validator\Constraints\email'
to
'Symfony\Component\Validator\Constraints\Email'
otherwise the autoloader can't find the file and the class.
It really was a error case of case sensitive, but I corrected the wrong one.
src/DbeDonaciBundle/Resources/config/validation.yml
Dbe\DonaciBundle\Entity\Newsletter:
properties:
email:
- Email :
message: The email "{{ value }}" is not a valid email.
checkMX: true