symfony2 isValid()返回false而没有错误

时间:2013-10-11 21:43:04

标签: forms validation symfony

 if ($editForm->isValid()) {

继续返回false但我没有收到任何错误消息。

我尝试了以下线程中的所有建议技术,例如我做

var_dump( $editForm->getErrorsAsString() );
die;

并获取

string(266) "name: No errors syncSchema: 1: No errors 12: No errors 37: No errors 38: No errors 49: No errors 14: No errors 39: No errors 76: No errors 152: No errors "

Symfony2 : How to get form validation errors after binding the request to the form

可能导致此行为的其他任何事情?

***更新(包含代码)*****

控制器

public function updateAction(Request $request, $id)
{
    $currentCompany = $this->container->get('security.context')->getToken()->getUser()->getCompany();

    $folderHelper = $this->get('biztv.helper.folderHelper'); 

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

    $entity = $em->getRepository('BizTVMediaManagementBundle:Video')->find($id);

    if (!$entity) {
        throw $this->createNotFoundException('Unable to find Video entity.');
    }
    if ($entity->getCompany() != $currentCompany) {
        throw $this->createNotFoundException('Unable to find Folder entity in THIS company.');
    }         

    $deleteForm = $this->createDeleteForm($id);
    $editForm = $this->createEditForm($entity);

    $folders = $folderHelper->getFolders(); 

    $editForm->handleRequest($request);

    if ($editForm->isValid()) {

       $entity->setCompany($currentCompany);

        //Get and check the folder chosen as parent
        $entity->setFolder( $folderHelper->checkFolderId($request->request->get('folder')) ); //will cause die() if folder doesn't belong to this company

        //Check which folder to go back to later on
        $goToFolder = $folderHelper->goToFolder($entity);          

        $helper = $this->get('biztv.helper.globalHelper');
        $helper->log('success', 'Videon <strong>'. $entity->getName() .'</strong> har uppdaterats.');

        $em->flush();

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

/**
* Creates a form to edit a Video entity.
*
* @param Video $entity The entity
*
* @return \Symfony\Component\Form\Form The form
*/
private function createEditForm(Video $entity)
{
    $currentCompanyId = $this->container->get('security.context')->getToken()->getUser()->getCompany()->getId();

    $form = $this->createForm(new VideoTypeEdit($currentCompanyId), $entity, array(
        'action' => $this->generateUrl('video_update', array('id' => $entity->getId())),
        'method' => 'PUT',
    ));

    return $form;
}

FormType

namespace BizTV\MediaManagementBundle\Form;

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

use Doctrine\ORM\EntityRepository;

class VideoTypeEdit extends AbstractType
{
        /**
     * @param FormBuilderInterface $builder
     * @param array $options
     */

    function __construct($company)
    {
        $this->company = $company;
    }

    public function buildForm(FormBuilderInterface $builder, array $options)
    {
        $company = $this->company;

        $builder
            ->add('name')
        ;

        $builder
            ->add('syncSchema', 'entity', array(
                'label' => ' ',
                'multiple' => true,   // Multiple selection allowed
                'expanded' => true,   // Render as checkboxes
                'property' => 'select_label',
                'class'    => 'BizTV\ContainerManagementBundle\Entity\Container',
                'query_builder' => function(\Doctrine\ORM\EntityRepository $er) use ($company) {
                    $qb = $er->createQueryBuilder('a');
                    $qb->innerJoin('a.containerType', 'ct');
                    $qb->where('a.containerType IN (:containers)', 'a.company = :company');
                    $qb->setParameters( array('containers' => array(1,2,3,4), 'company' => $company) );
                    $qb->orderBy('ct.id', 'ASC');

                    return $qb;
                }
            ));


    }

    /**
     * @param OptionsResolverInterface $resolver
     */
    public function setDefaultOptions(OptionsResolverInterface $resolver)
    {
        $resolver->setDefaults(array(
            'data_class' => 'BizTV\MediaManagementBundle\Entity\Video'
        ));
    }

    /**
     * @return string
     */
    public function getName()
    {
        return 'biztv_mediamanagementbundle_videoedit';
    }
}

查看

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

{% block contents -%}
    <h1>Video edit</h1>

    <div class="userAction_wrapper" style="width:800px;">

            {{ form_errors(edit_form.name) }}
            {{ form_errors(edit_form.syncSchema) }}

            {{ form_errors(edit_form) }}

        <form action="{{ path('video_update', { 'id': entity.id }) }}" method="post" {{ form_enctype(edit_form) }} novalidate>
            {{ form_widget(edit_form) }}

            <label for="folder">Mapp</label>
            <select name='folder'>
                    <option value='none'>Ingen mapp</option>
                    {% include 'BizTVMediaManagementBundle:Image:options.html.twig' with {'folders': folders, 'level': 0 } %}
            </select> 

            <div>
                <table>
                <tr>
                    <td>Längd</td>
                    <td>{{ entity.duration }}s</td>
                </tr>
                <tr>
                    <td>Bredd</td>
                    <td>{{ entity.width }}px</td>
                </tr>
                <tr>
                    <td>Höjd</td>
                    <td>{{ entity.height }}px</td>
                </tr>
                <tr>
                    <td>Codec</td>
                    <td>{{ entity.codec }}</td>
                </tr>
                <tr>
                    <td>Filstorlek</td>
                    <td>{{ entity.filesize }}bytes</td>
                </tr>               

                </table>
            </div>

            Välj vilka ställen videofilen skall kopieras till
            {% render(controller('BizTVContentManagementBundle:Default:index', {'userEdit': true}))  %} 

            <div>
                <button type="submit">Spara</button>
            </div>

        </form>

        <ul class="record_actions">
            <li>
                <a href="{{ path('video') }}">
                    Back to the list
                </a>
            </li>
            <li>{{ form(delete_form) }}</li>
        </ul>

    </div>


<script type="text/javascript">

$(function() {

$('#biztv_mediamanagementbundle_videoedit_syncSchema').children().each(function() {

        fromId = $(this).attr('id');

        if (typeof fromId != 'undefined') {
            Id = fromId.replace("biztv_mediamanagementbundle_videoedit_syncSchema_","");
            toId = 'container_'+Id;

            $('#'+toId).append( ' ' );
            $('#'+toId).append( $('#'+fromId) );

        }

    });     

$('#biztv_mediamanagementbundle_videoedit_syncSchema').remove();      

});

</script>
{% endblock %}

3 个答案:

答案 0 :(得分:3)

显然,在构建symfony2.3方式时,你需要在树枝上做这个,

{{ form_start(form) }}
   {{ form_errors(form) }}

   {{ form_row(form.task) }}
   {{ form_row(form.dueDate) }}
{{ form_end(form) }}

尽管如此,对于以老式方式构建的表单,您仍然可以用老式的方式将它们弄清楚。

答案 1 :(得分:1)

假设您使用Symfony 2.3,我认为您错过了模板中的form_end()(iirc在2.3之前称为form_rest())。查看当前的docmentation。因此,不要只是简单地写</form> form_end(edit_form),而应该使您的表单有效。

答案 2 :(得分:1)

考虑一下,你正在验证所显示的一切,没有显示的错误,所以有一些隐藏的东西需要验证:)

{{form_widget(form._token)}}? csrf检查?

btw form_rest!= form_end