hello everyone i have a rut field and i want to apply a validation to this field but dont know where.
my user class have id, rut(string) and name(string).
i have to create a new class to validate rut??
my usertype
class UsuariosType extends AbstractType
{
/**
* {@inheritdoc}
*/
public function buildForm(FormBuilderInterface $builder, array $options)
{
$builder->add('rut')
->add('nombre');
}
/**
* {@inheritdoc}
*/
public function configureOptions(OptionsResolver $resolver)
{
$resolver->setDefaults(array(
'data_class' => 'Paginas\UsuariosBundle\Entity\Usuarios'
));
}
/**
* {@inheritdoc}
*/
public function getBlockPrefix()
{
return 'paginas_usuariosbundle_usuarios';
}
}
controller
class DefaultController extends Controller
{
public function agregarAction()
{
$usuario=new Usuarios();
$form=$this->createForm(new UsuariosType(), $usuario);
$request = $this->getRequest();
if ($request->getMethod() == 'POST') {
$form->bind($this->getRequest());
if ($form->isValid()) {
$usuario=$form->getData();
$em=$this->getDoctrine()->getManager();
$em->persist($usuario);
$em->flush();
$product=$em->getRepository('PaginasUsuariosBundle:Usuarios')->findAll();
//redirecciona al listar
return $this->redirectToRoute('usuario_lista');
}
}
}
}
-
List item
return $this->render('PaginasUsuariosBundle:Default:crear_usuario.html.twig', array('form' => $form->createView() ));
and i found this on web.. but dont know how to use them to validate rut field.
rut.php
use Symfony\Component\Validator\Constraint;
use Symfony\Component\Validator\Exception\MissingOptionsException;
/**
* @Annotation
*/
class Rut extends Constraint
{
public $message = 'this value is not a valid RUT';
public function __construct($options = null)
{
parent::__construct($options);
}
}
rutvalidator.php
use Symfony\Component\Validator\Constraint;
use Symfony\Component\Validator\ConstraintValidator;
class RutValidator extends ConstraintValidator
{
/**
* {@inheritDoc}
*/
public function validate($value, Constraint $constraint)
{
$r = strtoupper(str_replace(array(".", "-"), "", $value));
$sub_rut = substr($r, 0, strlen($r) - 1);
$sub_dv = substr($r, - 1);
$x = 2;
$s = 0;
for ($i = strlen($sub_rut) - 1; $i >= 0; $i--) {
if ($x > 7) {
$x = 2;
}
$s += $sub_rut[$i] * $x;
$x++;
}
$dv = 11 - ($s % 11);
if ($dv == 10) {
$dv = 'K';
}
if ($dv == 11) {
$dv = '0';
}
if ($dv != $sub_dv) {
$this->context->addViolation($constraint->message, array('%string%' => $value));
}
}
}
could someone help me please where should i put those files (rut and rutvalidator) and how do i call them... is in the usertype or the controller??