【问题标题】:symfony2 isValid() returns false without errorssymfony2 isValid() 返回 false 没有错误
【发布时间】:2013-10-11 21:43:04
【问题描述】:

我的

 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;
}

表单类型

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 %}

【问题讨论】:

  • 请发布您的表单类型、实体等

标签: forms validation symfony


【解决方案1】:

显然,symfony2.3方式构建表单时,需要在twig中进行,

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

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

虽然,对于以老式方式构建的表单,您仍然可以使用老式方式 TWIG。

【讨论】:

    【解决方案2】:

    假设您使用 Symfony 2.3,我认为您在模板中错过了form_end()(iirc 在 2.3 之前称为 form_rest())。请参阅当前的docmentation。因此,不要简单地写 &lt;/form&gt; form_end(edit_form) 应该使您的表单有效。

    【讨论】:

    • 不幸的是没有变化..顺便说一句,当一个 {{ form_widget(edit_form) }} 时,不是包含 form_rest() (或 ...end)的东西吗?是的,大约一个月以来的 2.3.. 可怕的 BC 在该更新中中断..
    • @MattiasSvensson 是的,我知道。但是我找不到关于那个的任何文档(至少不是 2.3),所以我不再确定了。那么我最后的猜测是删除$deleteForm,也许它会以某种方式干扰?在旁注中,您没有更新实体管理器中的实体,因此您不会在 flush() 上保存任何更改。
    【解决方案3】:

    想一想,您正在验证显示的所有内容,显示的内容没有错误,所以有一些隐藏的东西需要验证:)

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

    顺便说一句 form_rest != form_end

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-01-13
      相关资源
      最近更新 更多