在symfon2 / Doctrine中处理dd / mm / yyyy格式

时间:2014-06-02 20:56:10

标签: symfony doctrine-orm

这里应该发生的是:

  • DOB 仅接受dd/mm/yyyy格式。
  • 如果给出的格式不同,则“ DoB字段必须具有有效格式”。消息应在屏幕上阅读此消息应来自 ENTITY 非形式TYPE 设置为' invalid_message '属性。

JFYI:我可以在entity中将 $ dob 定义为' string ',并将其作为' text < / em>'以type的形式使整个过程工作,但这不是好的做法。原因是我不希望数据库中的$ dob为varchar字段,我想要date字段。

PERSON ENTITY 注意:这是我希望进行表单验证的唯一地方):

namespace Se\HirBundle\Entity;

use Symfony\Component\Validator\Constraints as Assert;
use Doctrine\ORM\Mapping as ORM;

/**
 * Person
 * 
 * @ORM\Entity
 * @ORM\Table(name="person")
 * @ORM\HasLifecycleCallbacks
 */
class Person
{
    /**
     * @var integer $id
     * 
     * @ORM\Id
     * @ORM\Column(type="integer")
     * @ORM\GeneratedValue(strategy="AUTO")
     */
    protected $id;

    /**
     * @var string $firstname
     * 
     * @Assert\NotBlank(message = "The Firstname field should not be blank.")
     * @Assert\Length(max = "100", maxMessage = "The Firstname field cannot be longer than {{ limit }} characters length.")
     * 
     * @ORM\Column(type = "string", length = 100)
     */
    protected $firstname;

    /**
     * @var date $dob
     * 
     * @Assert\NotBlank(message = "The DoB field should not be blank.")
     * @Assert\Regex(pattern = "/^(0[1-9]|[12][0-9]|3[01])[\/\-](0[1-9]|1[012])[\/\-]\d{4}$/", message = "The DoB field must have a valid format.")
     * 
     * @ORM\Column(type = "date", length = 10)
     */
    protected $dob;

    /**
     * @var datetime $created
     *
     * @ORM\Column(type="datetime")
     */
    protected $created;

    /**
     * @var datetime $updated
     * 
     * @ORM\Column(type="datetime", nullable = true)
     */
    protected $updated;




    /**
     * Gets triggered only on insert
     * 
     * @ORM\PrePersist
     */
    public function onPrePersist()
    {
        $this->created = new \DateTime("now");
    }

    /**
     * Gets triggered every time on update
     * 
     * @ORM\PreUpdate
     */
    public function onPreUpdate()
    {
        $this->updated = new \DateTime("now");
    }




    /**
     * Get id
     *
     * @return integer 
     */
    public function getId()
    {
        return $this->id;
    }

    /**
     * Set firstname
     *
     * @param string $firstname
     * @return Person
     */
    public function setFirstname($firstname)
    {
        $this->firstname = $firstname;

        return $this;
    }

    /**
     * Get firstname
     *
     * @return string 
     */
    public function getFirstname()
    {
        return $this->firstname;
    }

    /**
     * Set dob
     *
     * @param string $dob
     * @return Person
     */
    public function setDob($dob)
    {
        $this->dob = $dob;

        return $this;
    }

    /**
     * Get dob
     *
     * @return string 
     */
    public function getDob()
    {
        return $this->dob;
    }
}

表单TYPE文件:

namespace Se\HirBundle\Form\Type\Person;

use Symfony\Component\Form\AbstractType;
use Symfony\Component\Form\FormBuilderInterface;
use Symfony\Component\OptionsResolver\OptionsResolverInterface;

class CreateType extends AbstractType
{
    public function buildForm(FormBuilderInterface $builder, array $options)
    {
        $builder
                ->setAction($options['action'])
                ->setMethod('POST')

                ->add('firstname', 'text',
                        array('label' => 'Firstname', 'error_bubbling' => true))

                ->add('dob', 'date',
                        array('label' => 'DoB', 'widget' => 'single_text',
                            'format' => 'dd/MM/yyyy', 'input'  => 'datetime', 'error_bubbling' => true))

                ->add('create', 'submit',
                        array('label' => 'Create Person'));
    }

    public function getName()
    {
        return 'personcreate';
    }

    public function setDefaultOptions(OptionsResolverInterface $resolver)
    {
        $resolver->setDefaults(array('data_class' => 'Se\HirBundle\Entity\Person'));
    }
}

控制器:

namespace Se\HirBundle\Controller;

use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use Se\HirBundle\Entity\Person;
use Se\HirBundle\Form\Type\Person\CreateType;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;

class CrudController extends Controller
{
    public function createAction()
    {
        $person = new Person();

        $form = $this->createForm(new CreateType(), $person,
                array('action' => $this->generateUrl('create_submit')));

        return $this->render('SeHirBundle:Default:create.html.twig',
                array('page' => 'Create', 'form' => $form->createView()));
    }

    public function createPersonAction(Request $request)
    {
        if ($request->getMethod() != 'POST')
        {
            return new Response('Only POST method is accepted');
        }

        $person = new Person();

        $form = $this->createForm(new CreateType(), $person,
                array('action' => $this->generateUrl('create_submit')));

        $form->handleRequest($request);

        if ($form->isValid())
        {
            $submission = $form->getData();

            $em = $this->getDoctrine()->getManager();

            $person = new Person();
            $person->setFirstname($submission->getFirstname());
            $person->setDob($submission->getDob());

            $em->persist($person);
            $em->flush();

            $this->get('session')->getFlashBag()->add('message', 'Person successfully created!');

            return $this->redirect($this->generateUrl('message'));
        }

        return $this->render('SeHirBundle:Default:create.html.twig',
                array('page' => 'Create', 'form' => $form->createView()));
    }
}

TWIG:

{% extends '::base.html.twig' %}

{% block title %}{{ page }}{% endblock %}


{% block body %}
    <b>{{ page|upper }}</b>
    <hr />
    {{ form_start(form, {attr: {novalidate:'novalidate'}}) }}
        {% if form_errors(form) != '' %}
            <div>{{ form_errors(form) }}</div>
        {% endif %}

        <div>
            {{ form_label(form.firstname) }}
            {{ form_widget(form.firstname) }}
        </div>

        <div>
            {{ form_label(form.dob) }}
            {{ form_widget(form.dob, {'type':'text'}) }}
        </div>

        <br />

        <div>
            {{ form_widget(form.create) }}
        </div>

    {{ form_end(form)}}
{% endblock %}

2 个答案:

答案 0 :(得分:1)

以下是基于Symfony2 documentation

的解决方案

控制器

文件的开头

use Symfony\Component\HttpFoundation\Response;

控制器中的功能

此控制器将显示dob字段,因为这是Datetime对象,需要使用format()才能显示它。这只是一个示例,表明Symfony2识别日期并在内部对其进行转换。

取消注释以//开头的行就足以将Person实体与dob一起保留。

public function testAction(Request $request)
{
    $person = new Person();

    $form = $this->createFormBuilder($person)
        ->add('dob', 'date',
            array(
                'label' => 'DoB',
                'widget' => 'single_text',
                'format' => 'dd/MM/yyyy',
                'invalid_message' => 'Validation error goes here',
                'error_bubbling' => true,
                'input' => 'datetime' # return a Datetime object (*)
            )
        )
        ->getForm();

    $form->handleRequest($request);

    if ($form->isValid()) {
        # perform some action, such as saving the task to the database
        //$em = $this->getDoctrine()->getManager();
        //$em->persist($person);
        //$em->flush();

        return new Response($person->getDob()->format('d-m-Y'));
    }

    return $this->render(
        'YourBundle:Default:test.html.twig',
        array(
            'form' => $form->createView()
        )
    );
}

(*):http://symfony.com/fr/doc/master/reference/forms/types/date.html#input

Twig文件

{{ form(form) }}

的routing.yml

test:
    pattern:  /test/
    defaults: { _controller: YourBundle:Default:test }

答案 1 :(得分:0)

控制器中的

解决方案:

$dob = date('Y-m-d', strtotime(str_replace('/', '-', $submission->getDob())));
$person->setDob($dob);