Symfony2 Constraints\email not found - validation

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

Related

Symfony 4/JMS/FOSUser: Can't serialize datas from FOS\UserBundle

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

Swiftmailer Symfony 3 : 1 email sent but nothing appear

I'm trying to send an email with symfony 3, swiftmailer and twig.
I'm doing a form with formbuilder and when someone click on the submit button, it send the mail. I don't have an error, only a "1 spooled message".
What I've tried : I did : php bin/console swiftmailer:email:send
It returns : [OK] 1 emails were successfully sent. (also here i've no mail).
In my two boxes I have allowed less restrictions for connexions.
My code looks like :
For the controller :
/**
* #Route("testmail", name="testmail")
*/
public function testmail(Request $request)
{
$societe = null;
$form = $this->createFormBuilder()
->add('Societe', TextType::class, array('label' => 'Société'), array('constraints' => array(new NotBlank(array()),
new Length(array('min' => 2,
'max' => 25)))))
-> add('send',SubmitType::class, array('label' => 'Cotation'))
->getForm();
$form->handleRequest($request);
if ($form->isValid()) {
if ($request->isMethod('POST')) {
$societe = $form["Societe"]->getData();
$message = \Swift_Message::newInstance()
->setSubject('Etude Financiere')
->setFrom('wolffvianney#gmail.com')
->setTo('vianney.wolff#yahoo.fr')
->setCharset('utf-8')
->setContentType('text/html')
->setBody($this->render('#gkeep/Finance/email.html.twig', array('Societe' => $societe)));
$this->get('mailer')->send($message);
}
}
return $this->render('#gkeep/Finance/finance.html.twig', array('form' =>$form->createView(),
'Societe'=>$societe));
}
the config.yml :
swiftmailer:
transport: '%mailer_transport%'
host: '%mailer_host%'
username: '%mailer_user%'
password: '%mailer_password%'
spool: { type: memory }
the parameters.yml :
mailer_transport: mail
mailer_host: smtp.gmail.com
mailer_user: wolffvianney#gmail.com
mailer_password: *mypasswordforwolffvianney#gmail.com*
secret: thesecret
the Finance/email.html.twig
<html>
hi
société : {{ Societe }}
</html>
if anyone has any advices or help, I can send other files if needed. I don't understand what is wrong, thanks for advance. (I also tried to delete the line spool{type:memory
it says then that 1 email has been sent but here also, I don't receive any mails.
Vianney
Try
php bin/console swiftmailer:spool:send --env={your_env}

Error Symfony 3 with Monolog & swift mailer

I have a problem with swift mailer and monolog on Symfony 3.0.2:
FatalThrowableError in appDevDebugProjectContainer.php line 4963:
Type error: Argument 1 passed to SymfonyBundleMonologBundleSwiftMailerMessageFactory_0000000079e53f2b00000001716bb61a50d0bc982eb9e83148fbcc469ab36a58::__construct() must be an instance of Swift_Mailer, instance of Closure given, called in /Users/Romain/Sites/var/cache/dev/appDevDebugProjectContainer.php on line 4043
# Swiftmailer Configuration config.yml
swiftmailer:
transport: "%mailer_transport%"
host: "%mailer_host%"
username: "%mailer_user%"
password: "%mailer_password%"
spool: { type: memory }
#Monolog config_prod.yml
monolog:
handlers:
main:
type: fingers_crossed
action_level: critical
handler: grouped
grouped:
type: group
members: [streamed, buffered]
streamed:
type: stream
path: "%kernel.logs_dir%/%kernel.environment%.log"
level: debug
buffered:
type: buffer
handler: swift
swift:
type: swift_mailer
from_email: no-reply#email.com
to_email: email#email.com
subject: "Subject"
level: debug
An extract appDevDebugProjectContainer.php on line 4963
/**
* {#inheritDoc}
*/
public function __construct(\Swift_Mailer $mailer, $fromEmail, $toEmail, $subject, $contentType = null)
{
static $reflection;
if (! $this->valueHolder56d41e956b1f5441039037) {
$reflection = $reflection ?: new \ReflectionClass('Symfony\\Bundle\\MonologBundle\\SwiftMailer\\MessageFactory');
$this->valueHolder56d41e956b1f5441039037 = $reflection->newInstanceWithoutConstructor();
\Closure::bind(function (\Symfony\Bundle\MonologBundle\SwiftMailer\MessageFactory $this) {
unset($this->mailer, $this->fromEmail, $this->toEmail, $this->subject, $this->contentType);
}, $this, 'Symfony\\Bundle\\MonologBundle\\SwiftMailer\\MessageFactory')->__invoke($this);
}
$this->valueHolder56d41e956b1f5441039037->__construct($mailer, $fromEmail, $toEmail, $subject, $contentType);
}
An extract appDevDebugProjectContainer.php on line 4043
/**
* Gets the 'monolog.handler.swift.mail_message_factory' service.
*
* This service is shared.
* This method always returns the same instance of the service.
*
* This service is private.
* If you want to be able to request this service from the container directly,
* make it public, otherwise you might end up with broken code.
*
* #param bool $lazyLoad whether to try lazy-loading the service with a proxy
*
* #return \Symfony\Bundle\MonologBundle\SwiftMailer\MessageFactory A Symfony\Bundle\MonologBundle\SwiftMailer\MessageFactory instance.
*/
public function getMonolog_Handler_Swift_MailMessageFactoryService($lazyLoad = true)
{
if ($lazyLoad) {
return $this->services['monolog.handler.swift.mail_message_factory'] = new SymfonyBundleMonologBundleSwiftMailerMessageFactory_0000000057f95edf000000015dd8d44e50d0bc982eb9e83148fbcc469ab36a58(
function (&$wrappedInstance, \ProxyManager\Proxy\LazyLoadingInterface $proxy) {
$wrappedInstance = $this->getMonolog_Handler_Swift_MailMessageFactoryService(false);
$proxy->setProxyInitializer(null);
return true;
}
);
}
return new \Symfony\Bundle\MonologBundle\SwiftMailer\MessageFactory($this->get('swiftmailer.mailer.default'), 'contact#domaine.com', array(0 => 'error#domaine.com'), 'Une erreur critique est survenue', NULL);
}
Sends him of e-mail with swiftmailer only work.
I already have this configuration with the same environment but symfony 2.7 and that works.
And this configuration works on a wamp (php7) but not on my environement OSX and server Linux ...
Thank you for your help
fix with symfony 3.0.3 and monolog 1.18

Creating a custom validator as a service in Symfony2

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

ValidationException on Update: Validation error whilst flushing entity on AbstractPersistenceEventListener

In my environment, i have grails.gorm.failOnError = true on Config.groovy.
package org.example
class Book {
String title
String author
String email
static constraints = {
title nullable: false, blank: false
email nullable: false, blank: false, unique: true //apparently this is the problem..
}
}
And, on controller, i have:
package org.example
class BookController {
def update() {
def bookInstance = Book.get(params.id)
if (!bookInstance) {
flash.message = message(code: 'default.not.found.message', args: [message(code: 'book.label', default: 'Book'), params.id])
redirect(action: "list")
return
}
if (params.version) {
def version = params.version.toLong()
if (bookInstance.version > version) {
bookInstance.errors.rejectValue("version", "default.optimistic.locking.failure",
[message(code: 'book.label', default: 'Book')] as Object[],
"Another user has updated this Book while you were editing")
render(view: "edit", model: [bookInstance: bookInstance])
return
}
}
bookInstance.properties = params
bookInstance.validate()
if(bookInstance.hasErrors()) {
render(view: "edit", model: [bookInstance: bookInstance])
} else {
bookInstance.save(flush: true)
flash.message = message(code: 'default.updated.message', args: [message(code: 'book.label', default: 'Book'), bookInstance.id])
redirect(action: "show", id: bookInstance.id)
}
}
}
To save, it's ok. But, when updating without set the title field, i get:
Message: Validation error whilst flushing entity [org.example.Book]:
- Field error in object 'org.example.Book' on field 'title': rejected value []; codes [org.example.Book.title.blank.error.org.example.Book.title,org.example.Book.title.blank.error.title,org.example.Book.title.blank.error.java.lang.String,org.example.Book.title.blank.error,book.title.blank.error.org.example.Book.title,book.title.blank.error.title,book.title.blank.error.java.lang.String,book.title.blank.error,org.example.Book.title.blank.org.example.Book.title,org.example.Book.title.blank.title,org.example.Book.title.blank.java.lang.String,org.example.Book.title.blank,book.title.blank.org.example.Book.title,book.title.blank.title,book.title.blank.java.lang.String,book.title.blank,blank.org.example.Book.title,blank.title,blank.java.lang.String,blank]; arguments [title,class org.example.Book]; default message [Property [{0}] of class [{1}] cannot be blank]
Line | Method
->> 46 | onApplicationEvent in org.grails.datastore.mapping.engine.event.AbstractPersistenceEventListener
- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
| 895 | runTask in java.util.concurrent.ThreadPoolExecutor$Worker
| 918 | run . . . . . . . in ''
^ 680 | run in java.lang.Thread
At q I understand it, the problem occurs when the flush hibernate session, hibernate tries to save the object again then the exception is thrown...
When trying to save the object again, is called the book.validate () again, which makes a new query in the database to ensure the uniqueness of the email field. Right now, the Validation Exception is thrown.
But, when i removed the unique validation of email property, the update is performed normally..
My question is: This behavior is correct? Hibernate calls book.save automatically?
This is the sample project, and the steps to simulate the error are:
source: https://github.com/roalcantara/grails_app_validation_exception
grails run-app
navigate to http:// localhost: 8080/ book/book/create
create an new instance filling all fields..
then edit this instance, in: http:// localhost: 8080/ book/book/edit/1
finally, drop the 'Title' field and click on Update, then the exception is thrown..
In my environment, this behavior has occurred on grails version 2.0.3 and 2.2.1
Thanks for any help! And sorry by my poor (and shame) english.. rs..
You are essentially validating twice, first with:
bookInstance.validate()
and second with:
bookInstance.save(flush: true)
When you call bookInstance.save(flush: true) a boolean is returned. Grails takes advantage of this by default when a controller is generated, but it appears you have changed the controller Grails generated by default for some reason.
Just replace this:
bookInstance.validate()
if(bookInstance.hasErrors()) {
render(view: "edit", model: [bookInstance: bookInstance])
} else {
bookInstance.save(flush: true)
flash.message = message(code: 'default.updated.message', args: [message(code: 'book.label', default: 'Book'), bookInstance.id])
redirect(action: "show", id: bookInstance.id)
}
With this:
if( !bookInstance.save( flush: true ) ) {
render(view: "edit", model: [bookInstance: bookInstance])
return
}

Resources