drtoclr046994545 2012-05-09 14:58
浏览 42

使用STI进行Symfony2表单验证(单表继承)

I'm building a web application using Symfony 2 framework in which I have a Notification class, subclassed by OrderCloseNotification and OrderDelayNotification using single table inheritance as described in Doctrine 2 documentation to serve slightly different purposes (as you can guess by the class name).

I need to validate the form submissions differently what lead me to create a custom type and controllers for each one of them. I'll use OrderDelayNotification as it's the type of Notification that needs validation. Here's my setup:

Super class:

# src/MyNamespace/MyBundle/Entity/Noticication.php
namespace MyNamespace\MyBundle\Entity;
use Doctrine\ORM\Mapping as ORM;

class Notification
{
    # common attributes, getters and setters
}

Subclass:

# src/MyNamespace/MyBundle/Entity/OrderDelayNotification.php
namespace MyNamespace\MyBundle\Entity;
use Doctrine\ORM\Mapping as ORM;

class OrderDelayNotification extends Notification
{
    private $message;
    # getters and setters
}

Subclass controller:

namespace MyNamespace\MyBundle\Controller;

use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use Symfony\Component\HttpFoundation\Response;

use MyNamespace\MyBundle\Entity\OrderDelayNotification;
use MyNamespace\MyBundle\Form\Type\OrderDelayNotificationType;


class OrderDelayNotificationController extends Controller
{    
    public function createAction() {

    $entity  = new OrderDelayNotification();
        $request = $this->getRequest();
        $form    = $this->createForm(new OrderDelayNotificationType(), $entity);
        $form->bindRequest($request);

        if ($form->isValid()) {
             //$em = $this->getDoctrine()->getEntityManager();
             //$em->persist($entity);
             //$em->flush();

        } else {

        }   

        // I'm rendering javascript that gets eval'ed on the client-side. At the moment, the js file is only displaying the errors for validation purposes  
        if ($request->isXmlHttpRequest()) {
            return $this->render('LfmCorporateDashboardBundle:Notification:new.js.twig', array('form' => $form->createView()));
        } else {
        return $this->redirect($this->generateUrl('orders_list'));
        }
    }
}

My custom form type

# src/MyNamespace/MyBundle/Form/Type/OrderDelayNotificationType.php
class OrderDelayNotificationType extends AbstractType
{
    public function buildForm(FormBuilder $builder, array $options)
    {

        $builder->add('message')
                ->add('will_finish_at', 'date')
                ->add('order', 'order_selector'); //*1

    return $builder;
    }

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

*1 : order_selector it's a custom type that I together with a Data Transformer that maps an Order into it's primary key so that the Notification is created in a table view of a given set of orders.

Finally, I have a validation.yml (I use YAML for every configuration)

# src/MyNamespace/MyBundle/Resources/config.validation.yml
MyNamespace\MyBundle\Entity\OrderDelayNotification:
    properties:
        message:
            - NotBlank: ~

What happens here is: when I try to create a OrderDelayNotification through AJAX (haven't tried html request) the order is always considered valid even if the message is blank. I've also tried to impose a minimum length, but without luck. I read through symfony's documentiation and they say that the validation is enabled by default. Also tried to change the attribute name on validation.yml to an invalid one and Symfony complains about it which means the file is loaded, and yet the validation is not happening.

Does anyone have any pointers on this?

EDIT: The ajax call is made like this:

$('form[data-remote="true"]').submit(function(event){
    $.ajax({
        type:       $(this).attr('method'),
        url:            $(this).attr('action'),
        data:       $(this).serialize(),
        success:    function(response) {
            eval(response)
        }
    });
    event.preventDefault();
});

Which yields:

# src/MyNamespace/MyBundle/Resources/views/Notification/new.js.twig
alert("{{ form_errors(form) }}");

And it's were I can see no errors are being thrown by Symfony's validator service (indirectly called by my AbstractType subclass, according to Symfony's documentation)

  • 写回答

1条回答 默认 最新

  • dongzhuo0895 2012-05-09 16:35
    关注

    Found out what the problem was. The form was actually not valid, but the errors weren't being displayed. I had to include the following option for each of the form fields:

    $builder->add('message', null, array('error_bubbling' => true))
    

    The errors now display correctly.

    评论

报告相同问题?

悬赏问题

  • ¥20 腾讯企业邮箱邮件可以恢复么
  • ¥15 有人知道怎么将自己的迁移策略布到edgecloudsim上使用吗?
  • ¥15 错误 LNK2001 无法解析的外部符号
  • ¥50 安装pyaudiokits失败
  • ¥15 计组这些题应该咋做呀
  • ¥60 更换迈创SOL6M4AE卡的时候,驱动要重新装才能使用,怎么解决?
  • ¥15 让node服务器有自动加载文件的功能
  • ¥15 jmeter脚本回放有的是对的有的是错的
  • ¥15 r语言蛋白组学相关问题
  • ¥15 Python时间序列如何拟合疏系数模型