I’ve created a new field (“responsavel”) on my db for this entity (“Multa”), “responsavel” is a foreign key to another table (Usuario) and I want it to be shown on my form as an select with just some objects (that’s why the $desligados
I’m passing to the front) for the user to choose and then pass it to the back.
I’ve been able to do it with $.post
but I’m doing other things after the submit is passed to the controller so I’ve included a $(this).unbind('submit').submit();
but now it’s like I’m submitting the form two times, and one of them is not submitting with the “responsavel” value.
This is my form:
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, ]); } }
this is what I have on my controller:
/** * @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 ]); }
what I’m doing on the front:
{% 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(); }); });
A example of one submit on my db:
Advertisement
Answer
As Jakumi recommended I used the EntityType::class to create a custom querybuilder, it returned what i wanted and as I’m using the formType to render all the fields I didn’t needed to do anything on the frontend to pass it to my controller.