如何从Symfony3中提交的表单中获取数据?

时间:2018-12-11 23:15:10

标签: php forms api symfony

我面对一些非常规的情况。

1)我有一个依赖列表,该列表由Symfony FormType呈现,如下所示: enter image description here

2)位置和说明字段取决于公司字段。

3)当我更改“公司”字段(onchange事件js)时,发出了ajax请求,该请求从数据库中检索数据并构建一个下拉列表。

4)但是在提交表单时出现错误: enter image description here

请帮助我解决此问题。预先感谢。

我的formType:

public function buildForm(FormBuilderInterface $builder, array $options)
{
    $builder
        ->add('hours')
        ->add('messageText', null, ['required' => false])
        ->add('company', null, [
            'choice_label' => 'name',
            'placeholder' => 'Please select company',
            'required' => true
        ])
        ->add('procedure', TextType::class, ['attr' => ['placeholder' => 'Please type code or description'] ])
        ->add('instruction', ChoiceType::class, ['mapped' => false])
        ->add('location', ChoiceType::class, ['mapped' => false])

    ;
}

public function configureOptions(OptionsResolver $resolver)
{
    $resolver->setDefaults(array(
        'data_class' => InstructionNotification::class
    ));
}

来自控制器的动作:

/**
 * @Route("/admin/api/instructions", name="admin_api_instructions")
 * @param Request $request
 * @return JsonResponse
 */
public function getInstructionsByCompanyId(Request $request)
{
    $id = $request->get('id');
    if (!$id) {
        return new JsonResponse('No data', 404);
    }

    $instructions = $this->getDoctrine()->getRepository('OctaneBundle:Instruction')->findInstructionsByCompanyId($id);

    return new JsonResponse($instructions);
}

findInstructionsByCompanyId($ id):

public function findInstructionsByCompanyId($id)
{
    $qb = $this->createQueryBuilder('i');
    if ($id) {
        $qb
            ->where('i.company = :id')
            ->setParameter('id', $id);
    }

    return $qb->getQuery()->getResult();
}

来自api的响应(即:admin / api / instructions?id = 1):

[{"id":2,"label":"First instruction"},{"id":3,"label":"First instruction"}]

如果您需要任何其他信息,请在下面留下评论。谢谢

2 个答案:

答案 0 :(得分:0)

Symfony的验证器希望您提交的表单具有提交的instructionlocation值,该值存在于在表单类型类中创建表单时提供的列表中。由于您未提供任何说明和位置选项,因此会收到验证错误。

要绕过此错误,您应在buildForm函数中以以下表单类型使用Symfony的Form Events

$builder->get('company')->addEventListener(
        FormEvents::POST_SUBMIT,
        function (FormEvent $event) {
            $company = $event->getForm()->getData();
            $form = $event->getForm()->getParent();
            $form->add('location', EntityType::class, array(
                'class' => Location::class,
                'query_builder' => function (EntityRepository $repo) use ($company) {
                    return $repo->createQueryBuilder('location')
                        ->where('location.company = :company')
                        ->setParameter('company', $company->getId());
                }
            ));
            $form->add('instruction', EntityType::class, array(
                'class' => Instruction::class,
                'query_builder' => function (EntityRepository $repo) use ($company) {
                    return $repo->createQueryBuilder('instruction')
                        ->where('instruction.company = :company')
                        ->setParameter('company', $company->getId());
                }
            ));
        }
    );

答案 1 :(得分:0)

感谢您的回答,但我发现了针对我案的更优雅的解决方案。所以,

现在

我的 formType

i = 135
idstring = 'dlROA_ct'+str(i)+'_lblROALINE'
dict1 = {'id': idstring}
result = soup.find('span', dict1).get_text()

FormattedSelectType:

public function buildForm(FormBuilderInterface $builder, array $options)
{
    $builder
        ...
        ->add('instruction', FormattedSelectType::class, ['class' => Instruction::class])
        ->add('location', FormattedSelectType::class, ['class' => Location::class])
    ;
}

Etities Location和Instruction实体实现JsonSerializable和自定义FormattedLabelInterface接口,并具有以下方法:

class FormattedSelectType extends AbstractType
{
    /**
     * {@inheritdoc}
     */
    public function configureOptions(OptionsResolver $resolver)
    {
        $resolver->setDefaults(array(
            'choice_label' => function (FormattedLabelInterface $entity) {
                return $entity->getFormattedLabel();
            }
        ));
    }

    /**
     * {@inheritdoc}
     */
    public function getParent()
    {
        return EntityType::class;
    }
}