Hello I have small problem. I've never done form validator in sf2 so I don't know where I should start. I have one field 'username' and it is unique in database so how can I try it?
My Code :
-> ENTITY
/**
* @var string $nick_allegro
*
* @ORM\Column(name="nick_allegro", type="string", length=255, unique=true, nullable=true)
*/
private $nick_allegro;
-> FORM
public function buildForm(FormBuilder $builder, array $options)
{
$builder
->add('nick_allegro')
;
}
public function getDefaultOptions(array $options) {
return array(
'data_class' => 'My\FrontendBundle\Entity\Licence',
);
}
-> Controller
/**
* Displays a form to create a new Licence entity.
*
* @Route("/new", name="licence_new")
* @Template()
*/
public function newAction()
{
$entity = new Licence();
$form = $this->createForm(new LicenceType(), $entity);
return array(
'entity' => $entity,
'form' => $form->createView()
);
}
/**
* Creates a new Licence entity.
*
* @Route("/create", name="licence_create")
* @Method("post")
* @Template("MyFrontendBundle:Licence:new.html.twig")
*/
public function createAction()
{
$entity = new Licence();
$request = $this->getRequest();
$form = $this->createForm(new LicenceType(), $entity);
$form->bindRequest($request);
if ($form->isValid()) {
$em = $this->getDoctrine()->getEntityManager();
$em->persist($entity);
$em->flush();
return $this->redirect($this->generateUrl('licence_show', array('id' => $entity->getId())));
}
return array(
'entity' => $entity,
'form' => $form->createView()
);
}
-> View
<form action="{{ path('licence_create') }}" method="post" {{
form_enctype(form) }}>
{{ form_widget(form) }}
<p>
<button type="submit">Create</button>
</p> </form>
You need to use Unique Entity in symfony to validate that a particular field in a model is unique.
To help you a little bit (if you have a field called nick
):
use Symfony\Component\Validator\Constraints as Assert;
use Doctrine\ORM\Mapping as ORM;
use Symfony\Bridge\Doctrine\Validator\Constraints\UniqueEntity;
/**
* @ORM\Entity
* @UniqueEntity("nick")
*/
class User
{
/**
* @var string $email
*
* @ORM\Column(name="nick", type="string", length=255, unique=true)
*/
private $nick;
Validation will directly take effect as you asserted the constraints in your entity.. Therefore, you can already check the validaiton in your controller.
if ( 'POST' === $request->getMethod()) {
$form->bind($request);
if ($form->isValid())
{
//do something if the form is valid
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With