【问题标题】:How to set default selected option for Entity Type select?如何为实体类型选择设置默认选择选项?
【发布时间】:2018-05-31 11:12:54
【问题描述】:

所以我试图在我的表单中设置一个选定的选项,但我似乎无法找到如何做到这一点。我用谷歌搜索了一下,一切似乎都适用于 Symfony2,其中 default 是一件事,而 Symfony4 似乎不再是这种情况。

我尝试过使用dataempty_data,但都没有选择正确的值..

# weirdly, setting to ['guru'] gets undefined index error,
# setting to $options doesn't error
->add('guru', EntityType::class, array(
    'class' => User::class,
    'choice_label' => 'username',
    'data' => $options['guru'] 
 ))

以及我如何传递 $options:

$form = $this->createForm(EditCategoryType::class, array('guru' => $guruName));

【问题讨论】:

  • Options 是 createForm 函数的第三个参数。第二个是要更新的对象(或其他东西)。 $form = $this->createForm(EditCategoryType::class, $myCategory, array('guru' => $guruName));
  • @ThisGuyHasTwoThumbs 如果您检查版本 2,3 和 4 的文档,您在表单中设置数据的方式没有改变。所以你可能对选项数组做错了。忘记你已经解决了你的问题,你可以发布动作和完整的表格来检查它吗?我只是认为你这样做是一种不好的不必要的做法。
  • EditCategoryType 的 data_class 参数值使用了什么?哪个实体名称?
  • 如果您在此处定义要编辑的对象,您可以获得更好的结果。我将尝试用一个例子来解释答案

标签: forms symfony symfony4


【解决方案1】:

因此,在@Juan I. Morales Pestana 的帮助下,我找到了答案,我将以下内容添加为答案而不是将其标记为正确的唯一原因是因为它的工作方式似乎略有不同现在..:

控制器现在读取(感谢@Juan):

$category = $this->getDoctrine()->getRepository(Category::class)->find($id);
$category->setGuru($category->getGuru());

$form = $this->createForm(EditCategoryType::class, $category);

我的 EditCategoryType 类:

->add('guru', EntityType::class, array(
    'class' => User::class,
    'choice_label' => 'username',
    'mapped' => false,
    'data' => $options['data']->getGuru()
))

更新的树枝模板:

{{ form_widget(form.guru, { 'attr': {'class': 'form-control'} }) }}

【讨论】:

    【解决方案2】:
    <a href="{{ path('register_new', { idpackage: p.id }) }}" class="btn_packages">
    
    //sends to form type the package id
    $fromPackage = '';
    if($request->query->get('idpackage')) {
    $fromPackage = $request->query->get('idpackage');
    }
    
    $form = $this->createForm(RegisterFormType::class, $register, ['fromPackage' => $fromPackage]);
    
    in formType set the param in options: 
    public function configureOptions(OptionsResolver $resolver)
    {
    $resolver->setDefaults([
    'data_class' => Register::class,
    'fromPackage' => null
    ]);
    }
    
    ->add('package',EntityType::class, [
    'label' => 'Select one item',
    'class' => Package::class,
    'choice_label' => function($package) {
        return $package->getTitle() . ' | crédits : ' . $package->getAmount();
    },
    'attr' => ['class' => 'input-text', ],
    'placeholder' => '...',
    'required' => false,
    'choice_attr' => function($package) use ($idFromPackage) {
        $selected = false;
        if($package->getId() == $idFromPackage) {
            $selected = true;
        }
        return ['selected' => $selected];
    },
    ])
    

    【讨论】:

      【解决方案3】:
      $parentCategory = $categoryRepository->repository->find(2);
      $category = new Category();
      $category->setParentCategory(parentCategory);
      $form = $this->createForm(CategoryType::class, $category);
      

      我们选择了预定义的顶级类别,如果你这样使用它就可以工作。

      【讨论】:

        【解决方案4】:

        试试这个: empty_data documentation

        【讨论】:

        • 请在提出建议之前阅读完整的文档... 此选项确定当提交的值为空(或缺失)时该字段将返回什么值。 如果在视图中呈现表单时没有提供初始值,则不会设置初始值问题是如何设置默认选择选项...
        【解决方案5】:

        正如我在我的 cmets 中所说,你做错了什么。我将解释所有过程:

        在控制器中调用表单

        $person = new Person();
        $person->setName('My default name');
        $form = $this->createForm('AppBundle\Form\PersonType', $person);
        $form->handleRequest($request);
        

        那么这里执行createForm函数就是代码

        Symfony\Bundle\FrameworkBundle\Controller\ControllerTrait

            protected function createForm($type, $data = null, array $options = array())
            {
                return $this->container->get('form.factory')->create($type, $data, $options);
            }
        

        如你所见,表单中没有直接设置数据或选项,调用另一个函数然后创建表单

        这是我在 PersonType 中进行转储时的结果

        PersonType.php on line 20:
        array:35 [▼
          "block_name" => null
          "disabled" => false
          "label" => null
          "label_format" => null
          "translation_domain" => null
          "auto_initialize" => true
          "trim" => true
          "required" => true
          "property_path" => null
          "mapped" => true
          "by_reference" => true
          "inherit_data" => false
          "compound" => true
          "method" => "POST"
          "action" => ""
          "post_max_size_message" => "The uploaded file was too large. Please try to upload a smaller file."
          "error_mapping" => []
          "invalid_message" => "This value is not valid."
          "invalid_message_parameters" => []
          "allow_extra_fields" => false
          "extra_fields_message" => "This form should not contain extra fields."
          "csrf_protection" => true
          "csrf_field_name" => "_token"
          "csrf_message" => "The CSRF token is invalid. Please try to resubmit the form."
          "csrf_token_manager" => CsrfTokenManager {#457 ▶}
          "csrf_token_id" => null
          "attr" => []
          "data_class" => "AppBundle\Entity\Person"
          "empty_data" => Closure {#480 ▶}
          "error_bubbling" => true
          "label_attr" => []
          "upload_max_size_message" => Closure {#478 ▶}
          "validation_groups" => null
          "constraints" => []
          "data" => Person {#407 ▼ // Here is the data!!!
            -id: null
            -name: "My default name"
            -salary: null
            -country: null
          }
        ]
        

        如您所见,数据在 data 处被索引,这就是您收到未定义索引错误的原因

        所以正确的方法是从控制器设置实体值或将您的表单用作服务并调用存储库并使用自版本 2 以来未更改的数据选项设置值。我的意思是您正在使用表格错误。

        请更改您的代码。

        希望对你有帮助

        以 SYMFONY 4 方式编辑(没有命名空间包)

        让我们看看,我有一个 Person 实体,其名称仅用于此示例

        控制器

            $person = new Person(); //or $personsRepository->find('id from request')
            $person->setName('My default name');
            $form = $this->createForm(PersonType::class, $person);
            $form->handleRequest($request);
        

        表格

        public function buildForm(FormBuilderInterface $builder, array $options)
            {
        
                $builder->add('name',TextType::class,[
                    //'data' => 'aaaaa' // <= this works too
        
                ]);
        
            }
        

        证明你访问错误的options数组值

        PersonType.php on line 20:
        array:35 [▼
          "block_name" => null
          "disabled" => false
          "label" => null
          "label_format" => null
          "translation_domain" => null
          "auto_initialize" => true
          "trim" => true
          "required" => true
          "property_path" => null
          "mapped" => true
          "by_reference" => true
          "inherit_data" => false
          "compound" => true
          "method" => "POST"
          "action" => ""
          "post_max_size_message" => "The uploaded file was too large. Please try to upload a smaller file."
          "error_mapping" => []
          "invalid_message" => "This value is not valid."
          "invalid_message_parameters" => []
          "allow_extra_fields" => false
          "extra_fields_message" => "This form should not contain extra fields."
          "csrf_protection" => true
          "csrf_field_name" => "_token"
          "csrf_message" => "The CSRF token is invalid. Please try to resubmit the form."
          "csrf_token_manager" => CsrfTokenManager {#457 ▶}
          "csrf_token_id" => null
          "attr" => []
          "empty_data" => Closure {#480 ▶}
          "error_bubbling" => true
          "label_attr" => []
          "upload_max_size_message" => Closure {#478 ▶}
          "validation_groups" => null
          "constraints" => []
          "data" => Person {#407 ▼
            -id: null
            -name: "My default name" //Here is the data
            -salary: null
            -country: null
          }
        ]
        

        AppBundle 只是我文件夹结构中的另一个文件夹。乐于测试自己。 formCreate 函数的第二个参数是实体或数据,而不是您认为选项是数据的选项。

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2014-11-18
          • 2015-09-19
          • 1970-01-01
          • 1970-01-01
          • 2017-12-11
          相关资源
          最近更新 更多