Reputation:
I am looking for a solution in my controller to check before sending a form if the user already exists in the database. Here is my action on which I would like to implement this.
/**
* Creates a new invite entity.
*
* @Route("/inscription", name="invite_new")
* @Method({"GET", "POST"})
*/
public function newAction(Request $request)
{
$invite = new Invite();
$form = $this->createForm(InviteType::class, $invite);
if ($request->isMethod('POST')) {
$form->handleRequest($request);
if ($form->isSubmitted() && $form->isValid()) {
$em = $this->getDoctrine()->getManager();
$em->persist($invite);
$em->flush();
$this->get('app_mailer')->sendMailInscriptionMjml($invite, $this->getParameter('client_mail_to'));
$this->get('session')->getFlashBag()->add('success', 'Votre inscription à été pris en compte.');
} else {
$this->get('session')->getFlashBag()->add('error', 'Une erreur est survenue.');
}
return $this->redirect($this->generateUrl('invite_show', array('id' => $invite->getId())));
}
return $this->render('@App/invite/new.html.twig', array(
'invite' => $invite,
'form' => $form->createView(),
));
}
Thank you for your help
Upvotes: 3
Views: 13759
Reputation: 5003
You shouldn't need to do this in the controller. This is basic entity validation and Symfony comes with built in constraints to handle this sort of thing.
Assuming you are using a User Entity similar to below in your Symfony application you need only apply a unique validation constraint to the user class and specify which properties you want to test against for uniqueness. This example will validate that the user is unique by email, and throw an exception if not.
// src/AppBundle/Entity/User.php
namespace AppBundle\Entity;
use Symfony\Component\Validator\Constraints as Assert;
use Doctrine\ORM\Mapping as ORM;
use Symfony\Bridge\Doctrine\Validator\Constraints\UniqueEntity;
/** @UniqueEntity(
* fields={"email"},
* errorPath="email",
* message="It appears you have already registered with this email."
*)
*/
class User
{
/**
* @ORM\Id
* @ORM\Column(type="integer")
* @ORM\GeneratedValue(strategy="AUTO")
*/
protected $id;
/**
* @var string $email
*
* @ORM\Column(name="email", type="string", length=255, unique=true)
* @Assert\Email()
*/
protected $email;
// ...
}
Pay notice to the @UniqueEntity("email")
annotation on the class and the use statements. Of course you'll need to adopt this logic to your user class.
// controller action
public function newAction(Request $request)
{
$invite = new Invite();
$form = $this->createForm(InviteType::class, $invite);
if ($request->isMethod('POST')) {
$form->handleRequest($request);
if ($form->isSubmitted() && $form->isValid()) {
$em = $this->getDoctrine()->getManager();
$em->persist($invite);
$em->flush();
$this->get('app_mailer')->sendMailInscriptionMjml(
$invite, $this->getParameter('client_mail_to')
);
$this->get('session')->getFlashBag()
->add('success', 'Votre inscription à été pris en compte.');
return $this->redirect(
$this->generateUrl(
'invite_show', array(
'id' => $invite->getId()
)
)
);
}
}
return $this->render('@App/invite/new.html.twig', array(
'invite' => $invite,
'form' => $form->createView(),
));
}
For more on this:
https://symfony.com/doc/current/reference/constraints/UniqueEntity.html
Upvotes: 7
Reputation:
<div class="container accroche">
<h5>{{ 'Inscription aux évenements'|trans }}</h5>
<p>Le Lorem Ipsum est simplement du faux texte employé dans la composition et la mise en page avant impression. Le Lorem Ipsum est le faux texte standard de l'imprimerie depuis les années 1500,
quand un peintre anonyme assembla ensemble des morceaux de texte pour réaliser un livre spécimen de polices de texte. Il n'a pas fait que survivre cinq siècles, mais s'est aussi adapté à la bureautique informatique,
sans que son contenu n'en soit modifié. Il a été popularisé dans les années 1960 grâce à la vente de feuilles Letraset contenant des passages du Lorem Ipsum, et, plus récemment,
par son inclusion dans des applications de mise en page de texte, comme Aldus PageMaker.
</p>
</div>
{{ form_start(form, {attr: {novalidate: 'novalidate','id':'formValidate'}}) }}
<div class="middle">
<div class="middle_form">
<div class="container">
<div class="stepwizard">
<div class="stepwizard-row setup-panel col-md-12 text-center">
<div class="stepwizard-step col-md-3">
<a href="#step-1" type="button" class="btn btn-primary btn-circle">1</a>
</div>
<div class="stepwizard-step col-md-3">
<a href="#step-2" type="button" class="btn btn-default btn-circle" disabled="disabled">2</a>
</div>
<div class="stepwizard-step col-md-3">
<a href="#step-3" type="button" class="btn btn-default btn-circle" disabled="disabled">3</a>
</div>
<div class="stepwizard-step col-md-3">
<a href="#step-4" type="button" class="btn btn-default btn-circle" disabled="disabled">4</a>
</div>
</div>
</div>
<div class="row setup-content" id="step-1">
<div class="col-md-12">
<h3>{{ 'Informations invités'|trans }}</h3>
<div class="row">
<div class="input-field col-12">
{{ form_widget(form.name, {'attr': {'class': 'validate', 'id': 'last_name'}}) }}
{{ form_errors(form.name) }}
<label for="last_name">{{ 'Nom'|trans }} <sup>*</sup></label>
</div>
</div>
<div class="row">
<div class="input-field col-12">
{{ form_widget(form.surname, {'attr': {'class': 'validate', 'id': 'surname'}}) }}
{{ form_errors(form.surname) }}
<label for="surname">{{ 'Prénom'|trans }} <sup>*</sup></label>
</div>
</div>
<div class="row">
<div class="input-field col-12">
{{ form_widget(form.email, {'attr': {'class': 'validate', 'id': 'email'}}) }}
{{ form_errors(form.email) }}
<label for="email">{{ 'E-mail'|trans }} <sup>*</sup></label>
</div>
</div>
<div class="row">
<div class="col-12">
<label>{{ 'Présence'|trans }} <sup>*</sup></label>
{{ form_widget(form.dispo, {'attr': {'class': 'validate', 'id': 'dispo'}}) }}
{{ form_errors(form.dispo) }}
</div>
</div>
<button class="btn btn-primary nextBtn btn-lg pull-right" type="button">{{ 'SUIVANT'|trans }}</button>
</div>
</div>
<div class="row setup-content" id="step-2">
<div class="col-md-12">
<h3>{{ 'Informations participants'|trans }}</h3>
<div class="row">
<ul class="customers"
data-prototype="{{ form_widget(form.customers.vars.prototype)|e('html_attr') }}">
{% for customers in form.customers %}
<div class="row">
<div class="input-field col-12">
{{ form_row(customers.name, {'attr': {'class': 'validate', 'id': 'name'}}) }}
{{ form_errors(customers.name) }}
</div>
</div>
<div class="row">
<div class="input-field col-12">
{{ form_row(customers.surname, {'attr': {'class': 'validate', 'id': 'surname'}}) }}
{{ form_errors(customers.surname) }}
</div>
</div>
<div class="row">
<div class="input-field col-12">
{{ form_row(customers.old) }}
{{ form_errors(customers.old) }}
</div>
</div>
{% endfor %}
</ul>
</div>
<button class="btn btn-primary prevBtn btn-lg pull-left" type="button">{{ 'PRECEDENT'|trans }}</button>
<button class="btn btn-primary nextBtn btn-lg pull-right" type="button">{{ 'SUIVANT'|trans }}</button>
</div>
</div>
<div class="row setup-content" id="step-3">
<div class="col-md-12">
<h3>Logements</h3>
<div class="row">
<div class="input-field col-12">
{{ form_widget(form.housing, {'attr': {'class':'validate'}}) }}
{{ form_errors(form.housing) }}
<label>{{ 'Comment allez vous vous logez ?'|trans }} <sup>*</sup></label>
</div>
</div>
<div class="row">
<div class="input-field col-12">
{{ form_widget(form.hotel, {'attr': {'class':'validate'}}) }}
{{ form_errors(form.hotel) }}
<label>{{ 'Hôtel'|trans }} <sup>*</sup></label>
</div>
</div>
<button class="btn btn-primary prevBtn btn-lg pull-left" type="button">{{ 'PRECEDENT'|trans }}</button>
<button class="btn btn-primary nextBtn btn-lg pull-right" type="button">{{ 'SUIVANT'|trans }}</button>
</div>
</div>
<div class="row setup-content" id="step-4">
<div class="col-md-12">
<h3>{{ 'Arrivée/Départ'|trans }}</h3>
<div class="row">
<div class="col-12">
<label>{{ 'Date d\'arrivée'|trans }} <sup>*</sup></label>
{#<input class="datepicker" type="text" id="dateArrival" name="form[dateArrival]"/>#}
{{ form_widget(form.dateArrival, {'attr': {'class': 'datepicker validate'}}) }}
{{ form_errors(form.dateArrival) }}
</div>
</div>
<div class="row">
<div class="col-12">
<label>{{ 'Date de départ'|trans }} <sup>*</sup></label>
{#<input class="datepicker" type="text" id="dateDeparture" name="form[dateDeparture]"/>#}
{{ form_widget(form.dateDeparture, {'attr': {'class': 'datepicker validate'}}) }}
{{ form_errors(form.dateDeparture) }}
</div>
</div>
<div class="row">
<div class="input-field col-12">
{{ form_widget(form.transport, {'attr': {'class':'validate'}}) }}
{{ form_errors(form.transport) }}
<label>{{ 'Transport utilisé'|trans }} <sup>*</sup></label>
</div>
</div>
<div class="btn-center">
<button class="btn btn-primary prevBtn btn-lg pull-left" type="button">{{ 'PRECEDENT'|trans }}</button>
{{ form_widget(form.save, {'attr': {'class':'btn btn-success', 'id':'SaveAccount'}}) }}
</div>
</div>
</div>
</div>
</div>
</div>
{{ form_widget(form.dateArrival, {'attr': {'class': 'hidden'}}) }}
{{ form_widget(form.dateDeparture, {'attr': {'class': 'hidden'}}) }}
{{ form_end(form) }}
Upvotes: 0
Reputation: 448
// Pass in the entity manager to your form via options
// Do this before you call $this->createForm:
// $options['entityManager'] = $this->getDoctrine()->getManager();
// then call $form = $this->createForm(InviteType::class, $invite, $options);
// Inside your form type i.e. InviteType
$em = $options['entityManager'];
$builder->addEventListener(
FormEvents::PRE_SUBMIT,
function (FormEvent $event) {
$data = $event->getData();
$form = $event->getForm();
$user = $data['user']; // this needs to be whatever you called user in your form
$userRepo = $em->getRepository('User'); // this needs to be the location of your user repository
if ($userRepo->findOneBy(['user' => $user])) { // you need to pick a field that determines how you will search for the user via the repository
$form->addError(new FormError('User already exists'));
}
}
);
Upvotes: 1
Reputation: 420
First, get the id $id = #YourId;
. You can then select the user using SQL. SELECT * FROM [user_table] WHERE id = $id;
If the result holds a user, then the user exists.
Upvotes: -1