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.

    评论

报告相同问题?

悬赏问题

  • ¥15 keil的map文件中Image component sizes各项意思
  • ¥30 BC260Y用MQTT向阿里云发布主题消息一直错误
  • ¥20 求个正点原子stm32f407开发版的贪吃蛇游戏
  • ¥15 划分vlan后,链路不通了?
  • ¥20 求各位懂行的人,注册表能不能看到usb使用得具体信息,干了什么,传输了什么数据
  • ¥15 Vue3 大型图片数据拖动排序
  • ¥15 Centos / PETGEM
  • ¥15 划分vlan后不通了
  • ¥20 用雷电模拟器安装百达屋apk一直闪退
  • ¥15 算能科技20240506咨询(拒绝大模型回答)