通过 post 将外键 ID 传递给表单

pass id of foreign key to the form via post

我在我的数据库上为这个实体(“Multa”)创建了一个新字段(“responsavel”),“responsavel”是另一个 table (Usuario) 的外键,我想要它在我的表单上显示为一个 select,只有一些对象(这就是我将 $desligados 传递到前面的原因)供用户选择,然后将其传递到后面。

我已经能够用 $.post 做到这一点,但在提交传递给控制器​​后我正在做其他事情所以我已经包含了一个 $(this).unbind('submit').submit(); 但现在就像我我提交了两次表单,其中一次没有使用“responsavel”值提交。

这是我的表格:

class MultaType extends AbstractType
{
    public function buildForm(FormBuilderInterface $builder, array $options)
    {
        $builder
            ->add('usuario')
            ->add('departamento')
            ->add('cliente')
            ->add('responsavel',null, ['attr'=>['style'=>'display:none;'], 'label'=> false])
            ->add('razaoSocial', null, ['label'=>'Cliente'])
            ->add('valor',null, ['label'=>'Valor Pago'])
            ->add('tipoPagamento', ChoiceType::class, ['choices'=>['Selecionar'=>0,'Integral'=>1,'Somente Encargos'=>2], 'required' => true], ['label' => 'Tipo de Pagamento'])
            ->add('dtRegistro', DateTimeType::class, ['widget'=>'single_text','input' => 'datetime','html5'=>false, 'label'=>'Data de Registro'])
            ->add('competencia', null, ['label'=>'Competência'])
            ->add('motivo', TextareaType::class, ['required'=>true])
            ->add('dtCiencia', DateTimeType::class, ['widget'=>'single_text','input' => 'datetime','html5'=>false, 'label'=>'Data de Ciência'])
            ->add('vistoCiencia', CheckboxType::class, ['label'=>'Ciente', 'required'=>false])
            ->add('nomeCliente', null, ['label'=>'Nome'])
            ->add('getRegistro', null, ['label'=>'CNPJ/CPF'])
            ->add('cpfCliente', null, ['label'=>'CPF'])
            ->add('cnpjCliente', null, ['label'=>'CNPJ'])

        ;
    }

    public function configureOptions(OptionsResolver $resolver)
    {
        $resolver->setDefaults([
            'data_class' => Multa::class,
            'usuario' => Usuario::class,
        ]);
    }
}

这是我控制器上的:

    /**
     * @Route("/novo", name="multa_novo", methods={"GET","POST"})
     */
    public function novo(PushNotification $push,
        Request $request): Response
    {   
        $multa = new Multa();
        $form = $this->createForm(MultaType::class, $multa);
        $form->remove('usuario');
        $form->remove('departamento');
        $form->remove('dtCiencia');
        $form->remove('dtRegistro');
        $form->remove('razaoSocial');
        $form->remove('getRegistro');

        if(in_array($this->getUser()->getAcesso(), [1,2,3,4,7,10]))
        {
            $desligados = $this->getDoctrine()->getRepository(Usuario::class)->findByAtivo(0);
        }
        else
        {
            $desligados = [];
        }
        $form->handleRequest($request);

        if ($form->isSubmitted() && $form->isValid()) {
            $entityManager = $this->getDoctrine()->getManager();
            $multa->setUsuario($this->getUser());
            $entityManager->persist($multa);
            $entityManager->flush();
            $this->addFlash('success', "Multa registrada com sucesso!");
 
 - "HERE I HAVE OTHER THINGS I'M DOING AFTER THE SUBMIT..." -

            return $this->redirectToRoute('multa_index');
        }

        return $this->render('multa/novo.html.twig', [
            'entity' => $multa,
            'form' => $form->createView(),
            'coordenador' => $coordenador[0], //passando o primeiro objeto usuario encontrado para o front
            'desligados' => $desligados
        ]);
    }

我在前面做什么:

            {% if desligados %}
            <div class="col-lg-4 mb-3" data-intro="Nome do coordenador responsável pela ciência da multa." data-step="5">
              <label>Responsável  <i class=" ml-1 text-info icon-sm mdi mdi-information-outline" title="Caso o responsável pela multa ja tenha sido desligado." data-placement="top" data-toggle="tooltip"></i></label>
              <select id="responsavel" name="multa[responsavel]" class="form-control">
                  <option></option>
                {% for responsavel in desligados %}
                  <option value="{{responsavel.id}}">{{ responsavel.nomeCompleto }}</option>
                {% endfor %}
              </select>
            </div>
            {% else %}

...


 $(function () {
      $("#multaForm").submit(function(e) {    
        e.preventDefault();
        e.stopPropagation();
        var form = $("#multaForm").serializeObject(); //Envia todo o formuário
        form['multa[responsavel]'] = $('#responsavel').val();

        $.post( {% if __rota[1] == 'novo' %} "{{ path('multa_novo') }}" {% elseif __rota[1] == 'editar' %} "{{ path('multa_editar', {'id': entity.id } ) }}" {% else %} "{{ path('multa_aprovacao', {'id': entity.id } ) }}" {% endif %}, form, function( data ) {
        }).fail(function(error) {
          console.log(error);
        });
        $(this).unbind('submit').submit();
        });
  });

我的数据库上的一个提交示例:

正如 Jakumi 所建议的那样,我使用 EntityType::class 创建了一个自定义查询生成器,它返回了我想要的内容,并且因为我使用 formType 来呈现所有字段,所以我不需要对前端将其传递给我的控制器。