symfony-forms 相关问题

Symfony表单组件是一个独立的库,可以在Symfony项目之外使用。

Symfony2动态分配attr到表单字段

我希望能够动态设置表单的 required=true/false 选项或数组(...其他东西...,'class' => 'hidden')场地。 上下文如下:...

回答 2 投票 0

从类型twig模板中的FormType访问变量

我创建了一个像这样的自定义表单类型: PositioningFlashType 类扩展 AbstractType { 噗...

回答 1 投票 0

如何使用 Symfony Forms 设置 API 的默认值?

我有一个非常简单的API。您可以将价格(价值和货币)发布到 API。默认货币为欧元,因此可以省略该货币。 API 返回完整价格对象: $curl -d '{"va...

回答 1 投票 0

Symfony Forms 手动提交 GET 和 POST 请求

有没有办法从Request类中获取合并数据?因为目前我们正在为接受 POST 和 GET 查询的 API 控制器手动提交表单(这不是 REST API,因为......

回答 1 投票 0

Symfony 表单:如何根据实体的其他属性设置动态选择?

我有一个表单类型 类 ArticleTranslationType 扩展 AbstractType { 公共函数 buildForm(FormBuilderInterface $builder, array $options): void { $builder ->添加('

回答 1 投票 0

Symfony 自定义字段类型与数据转换器在嵌入式集合表单中无法正常工作

我在 Symfony 中在自定义表单字段上使用自定义数据转换器时遇到问题 - 但仅当它在我的主表单中的集合/嵌入表单中使用时才出现问题。如果我使用相同的自定义字段...

回答 1 投票 0

Symfony2 表单在 buidler 中定义相同属性时会忽略自定义字段中的属性

当我在表单生成器中定义属性并在自定义字段中定义与默认属性相同的属性时,其他属性将被忽略。在表单生成器中我有: $builder ->添加('validityOfADecisionOnDisab...

回答 4 投票 0

提交表单时如何从URL中删除表单名称?

我有一个简单的 Symfony3 表单,但正如预期的那样,当表单被 GETed 时,它会生成一个包含表单名称的丑陋 url。像这样的东西: ...php?party_form%5Bplace%5D=米兰&party_form%5Bdate...

回答 2 投票 0

输入金额时输入空格 金钱类型 symfony

我想在输入这样的金额时输入空格。我必须使用 JavaScript 吗? 感谢您的帮助,请在此处输入图像描述

回答 1 投票 0

属性路径“id_autoridad”给出的预期参数类型为“int”、“App\Entity\Autoridad”

当我在 symofny 6 上工作时,我想执行此表单: 当我正在开发 symofny 6 时,我想执行此表单: <?php namespace App\Form; use App\Entity\Autoridad; use App\Entity\BalanceAnual; use Doctrine\DBAL\Types\IntegerType; use Doctrine\ORM\EntityRepository; use Symfony\Bridge\Doctrine\Form\Type\EntityType; use Symfony\Component\Form\AbstractType; use Symfony\Component\Form\Extension\Core\Type\ChoiceType; use Symfony\Component\Form\Extension\Core\Type\NumberType; use Symfony\Component\Form\FormBuilderInterface; use Symfony\Component\OptionsResolver\OptionsResolver; class BalanceAnualType extends AbstractType { public function buildForm(FormBuilderInterface $builder, array $options): void { $id_partido = $options['id_partido']; $autoridades = $options['autoridades']; #dd($id_partido); $builder ->add('id_partido') ->add('presentacion_anual') ->add('ejercicio') ->add('dia_cierre_ejercicio') ->add('mes_cierre_ejercicio') ->add('anio_ejercicio') ->add('fecha_presentacion') ->add('aprobacion',ChoiceType::class, ['choices' => [ 'SI' => 'S', 'NO' => 'N', ]]) ->add('fecha_aprobacion') ->add('id_autoridad', ChoiceType::class,[ 'choices'=> $autoridades, 'choice_label' => function ($autoridad) { if(strlen($autoridad->getApellido_Nombre())> 0){ echo("<script>console.log('idAutoridad: " . $autoridad->getId() ."');</script>"); return $autoridad->getApellido_Nombre(); }elseif(strlen($autoridad->getNombre())> 0){ echo("<script>console.log('idAutoridad: " . $autoridad->getId() ."');</script>"); return $autoridad->getNombre() ." ".$autoridad->getApellido(); }else{ return $autoridad->getId(); } }, 'choice_value' =>'id' ]) ->add('firmante_balance') ->add('movimentos',ChoiceType::class, ['choices' => [ 'SI' => 'S', 'NO' => 'N', ]]) ; } public function configureOptions(OptionsResolver $resolver): void { $resolver->setDefaults([ 'data_class' => BalanceAnual::class, 'id_partido' => null, 'autoridades' => null, ]); } } 表单以我想要的方式显示所有信息,但是当我想推送数据时,我收到以下错误:属性路径“id_autoridad”给出的预期参数类型为“int”,“App\Entity\Autoridad”。 我的实体: <?php namespace App\Entity; use App\Repository\BalanceAnualRepository; use Doctrine\DBAL\Types\Types; use Doctrine\ORM\Mapping as ORM; #[ORM\Entity(repositoryClass: BalanceAnualRepository::class)] class BalanceAnual { #[ORM\Id] #[ORM\GeneratedValue] #[ORM\Column] private ?int $id = null; #[ORM\Column()] private ?int $id_partido = null; #[ORM\Column()] private ?int $presentacion_anual = null; #[ORM\Column] private ?int $ejercicio = null; #[ORM\Column(length: 2)] private ?int $dia_cierre_ejercicio = null; #[ORM\Column(length: 2)] private ?int $mes_cierre_ejercicio = null; #[ORM\Column(length: 4)] private ?int $anio_ejercicio = null; #[ORM\Column(type: Types::DATE_MUTABLE)] private ?\DateTimeInterface $fecha_presentacion = null; #[ORM\Column(length: 1)] private ?string $aprobacion = null; #[ORM\Column(type: Types::DATE_MUTABLE)] private ?\DateTimeInterface $fecha_aprobacion = null; #[ORM\Column] private ?int $id_autoridad = null; #[ORM\Column(length: 100)] private ?string $firmante_balance = null; #[ORM\Column(length: 1)] private ?string $movimentos = null; /*#[ORM\ManyToOne(targetEntity: Autoridad::class)] #[ORM\JoinColumn(name: 'id_autoridad', referencedColumnName: 'id')] private $autoridad; #[ORM\ManyToOne(targetEntity: Partido::class)] #[ORM\JoinColumn(name: 'id_partido', referencedColumnName: 'id')] private $partido;*/ public function getId(): ?int { return $this->id; } public function getId_Partido(): ?int{ return $this->id_partido; } public function setId_Partido(int $id_partido): static { $this->id_partido=$id_partido; return $this; } public function getIdPartido(): ?int { return $this->id_partido; } public function setIdPartido(int $id_partido): static { $this->id_partido = $id_partido; return $this; } public function getPresentacion_Anual(): ?string { return $this->presentacion_anual; } public function setPresentacion_Anual(string $presentacion_anual): static { $this->presentacion_anual = $presentacion_anual; return $this; } public function getPresentacionAnual(): ?string { return $this->presentacion_anual; } public function setPresentacionAnual(string $presentacion_anual): static { $this->presentacion_anual = $presentacion_anual; return $this; } public function getEjercicio(): ?int { return $this->ejercicio; } public function setEjercicio(int $ejercicio): static { $this->ejercicio = $ejercicio; return $this; } public function getDia_Cierre_Ejercicio(): ?int { return $this->dia_cierre_ejercicio; } public function setDia_Cierre_Ejercicio(int $dia_cierre_ejercicio): static { $this->dia_cierre_ejercicio = $dia_cierre_ejercicio; return $this; } public function getDiaCierreEjercicio(): ?int { return $this->dia_cierre_ejercicio; } public function setDiaCierreEjercicio(int $dia_cierre_ejercicio): static { $this->dia_cierre_ejercicio = $dia_cierre_ejercicio; return $this; } public function getMes_cierre_ejercicio(): ?int { return $this->mes_cierre_ejercicio; } public function setMes_cierre_ejercicio(int $mes_cierre_ejercicio): static { $this->mes_cierre_ejercicio = $mes_cierre_ejercicio; return $this; } public function getMesCierreEjercicio(): ?int { return $this->mes_cierre_ejercicio; } public function setMesCierreEjercicio(int $mes_cierre_ejercicio): static { $this->mes_cierre_ejercicio = $mes_cierre_ejercicio; return $this; } public function getAnio_Ejercicio(): ?int { return $this->anio_ejercicio; } public function setAnio_Ejercicio(int $anio_ejercicio): static { $this->anio_ejercicio = $anio_ejercicio; return $this; } public function getAnioEjercicio(): ?int { return $this->anio_ejercicio; } public function setAnioEjercicio(int $anio_ejercicio): static { $this->anio_ejercicio = $anio_ejercicio; return $this; } public function getFecha_Presentacion(): ?\DateTimeInterface { return $this->fecha_presentacion; } public function setFecha_Presentacion(\DateTimeInterface $fecha_presentacion): static { $this->fecha_presentacion = $fecha_presentacion; return $this; } public function getFechaPresentacion(): ?\DateTimeInterface { return $this->fecha_presentacion; } public function setFechaPresentacion(\DateTimeInterface $fecha_presentacion): static { $this->fecha_presentacion = $fecha_presentacion; return $this; } public function getAprobacion(): ?string { return $this->aprobacion; } public function setAprobacion(string $aprobacion): static { $this->aprobacion = $aprobacion; return $this; } public function getFecha_Aprobacion(): ?\DateTimeInterface { return $this->fecha_aprobacion; } public function setFecha_Aprobacion(\DateTimeInterface $fecha_aprobacion): static { $this->fecha_aprobacion = $fecha_aprobacion; return $this; } public function getFechaAprobacion(): ?\DateTimeInterface { return $this->fecha_aprobacion; } public function setFechaAprobacion(\DateTimeInterface $fecha_aprobacion): static { $this->fecha_aprobacion = $fecha_aprobacion; return $this; } public function getId_autoridad(): ?int { return $this->id_autoridad; } public function setId_autoridad(int $id_autoridad): static { $this->id_autoridad = $id_autoridad; return $this; } public function getIdAutoridad(): ?int { return $this->id_autoridad; } public function setIdAutoridad(int $id_autoridad): static { $this->id_autoridad = $id_autoridad; return $this; } public function getFirmante_Balance(): ?string { return $this->firmante_balance; } public function setFirmante_Balance(string $firmante_balance): static { $this->firmante_balance = $firmante_balance; return $this; } public function getFirmanteBalance(): ?string { return $this->firmante_balance; } public function setFirmanteBalance(string $firmante_balance): static { $this->firmante_balance = $firmante_balance; return $this; } public function getMovimentos(): ?string { return $this->movimentos; } public function setMovimentos(string $movimentos): static { $this->movimentos = $movimentos; return $this; } } 我的控制器: #[Route('/{idPartido}/detalle/new', name: 'app_balance_anual_new', methods: ['GET', 'POST'])] public function new($idPartido,Request $request, EntityManagerInterface $entityManager): Response { $id_partido = intval($idPartido); $balanceAnual = new BalanceAnual(); $autoridades = $entityManager->getRepository(Autoridad::class)->findBy(['id_partido' => $id_partido]); #dd($autoridades); $form = $this->createForm(BalanceAnualType::class, $balanceAnual, ['id_partido' => $idPartido, 'autoridades' => $autoridades]); $form->get('id_partido')->setData($idPartido); #dd($form->getData(), $form->getErrors()); // print_r($request); $form->handleRequest($request); if ($form->isSubmitted() && $form->isValid()) { //dd($balanceAnual); $value = $form->get('id_autoridad')->getData(); $balanceAnual->setIdAutoridad($value); $entityManager->persist($balanceAnual); #dd($balanceAnual); $entityManager->flush(); return $this->redirectToRoute('app_balance_anual_index', ['idPartido' => $idPartido,], Response::HTTP_SEE_OTHER); } return $this->render('balance_anual/new.html.twig', [ 'balance_anual' => $balanceAnual, 'idPartido' => $idPartido, 'form' => $form, ]); } 另外两个实体:Partido: <?php namespace App\Entity; use App\Repository\PartidoRepository; use Doctrine\DBAL\Types\Types; use Doctrine\ORM\Mapping as ORM; #[ORM\Entity(repositoryClass: PartidoRepository::class)] class Partido { #[ORM\Id] #[ORM\GeneratedValue] #[ORM\Column] private ?int $id = null; #[ORM\Column(length: 100)] private ?string $nombre = null; #[ORM\Column] private ?int $numero = null; #[ORM\Column(length: 1)] private ?string $ambito = null; #[ORM\Column(length: 100)] private ?string $domicilio = null; #[ORM\Column] private ?int $id_localidad = null; #[ORM\Column(length: 255)] private ?string $domicilio_partidario = null; #[ORM\Column] private ?int $id_localidad_domicilio_partidario = null; #[ORM\Column(length: 100)] private ?string $telefono = null; #[ORM\Column(length: 100)] private ?string $email = null; #[ORM\Column(length: 1)] private ?string $tipo = null; #[ORM\Column(length: 2)] private ?string $estado = null; #[ORM\Column(length: 255)] private ?string $observaciones = null; #[ORM\Column(length: 1)] private ?string $libros = null; #[ORM\Column(length: 1)] private ?string $tipo_firma = null; #[ORM\Column(type: Types::DATE_MUTABLE)] private ?\DateTimeInterface $fecha_presentacion = null; #[ORM\Column] private ?int $id_localidad_ambito = null; #[ORM\Column] private ?int $id_auto_provisorio = null; #[ORM\Column(type: Types::DATE_MUTABLE)] private ?\DateTimeInterface $notificacion_auto_provisorio = null; #[ORM\Column(type: Types::DATE_MUTABLE)] private ?\DateTimeInterface $publicacion_boletin_oficial = null; #[ORM\Column] private ?int $id_auto_definitivo = null; #[ORM\Column(type: Types::DATE_MUTABLE)] private ?\DateTimeInterface $notificacion_auto_definitivo = null; #[ORM\Column] private ?int $id_auto_caducidad = null; #[ORM\Column(length: 255)] private ?string $observacion_caducidad = null; #[ORM\Column] private ?int $id_expediente = null; #[ORM\Column] private ?int $renueva_interna = null; #[ORM\Column] private ?int $id_extincion = null; #[ORM\Column] private ?int $codigo_postal = null; #[ORM\Column] private ?int $anio_exp_electronico = null; #[ORM\Column] private ?int $nro_exp_electronico = null; #[ORM\Column(type: Types::BIGINT)] private ?string $cuil_apoderado_notif = null; public function getId(): ?int { return $this->id; } public function getNombre(): ?string { return $this->nombre; } public function setNombre(string $nombre): static { $this->nombre = $nombre; return $this; } public function getNumero(): ?int { return $this->numero; } public function setNumero(int $numero): static { $this->numero = $numero; return $this; } public function getAmbito(): ?string { return $this->ambito; } public function setAmbito(string $ambito): static { $this->ambito = $ambito; return $this; } public function getDomicilio(): ?string { return $this->domicilio; } public function setDomicilio(string $domicilio): static { $this->domicilio = $domicilio; return $this; } public function getIdLocalidad(): ?int { return $this->id_localidad; } public function getId_Localidad(): ?int { return $this->id_localidad; } public function setIdLocalidad(int $id_localidad): static { $this->id_localidad = $id_localidad; return $this; } public function getDomicilioPartidario(): ?string { return $this->domicilio_partidario; } public function setDomicilioPartidario(string $domicilio_partidario): static { $this->domicilio_partidario = $domicilio_partidario; return $this; } public function getIdLocalidadDomicilioPartidario(): ?int { return $this->id_localidad_domicilio_partidario; } public function setIdLocalidadDomicilioPartidario(int $id_localidad_domicilio_partidario): static { $this->id_localidad_domicilio_partidario = $id_localidad_domicilio_partidario; return $this; } public function getTelefono(): ?string { return $this->telefono; } public function setTelefono(string $telefono): static { $this->telefono = $telefono; return $this; } public function getEmail(): ?string { return $this->email; } public function setEmail(string $email): static { $this->email = $email; return $this; } public function getTipo(): ?string { return $this->tipo; } public function setTipo(string $tipo): static { $this->tipo = $tipo; return $this; } public function getEstado(): ?string { return $this->estado; } public function setEstado(string $estado): static { $this->estado = $estado; return $this; } public function getObservaciones(): ?string { return $this->observaciones; } public function setObservaciones(string $observaciones): static { $this->observaciones = $observaciones; return $this; } public function getLibros(): ?string { return $this->libros; } public function setLibros(string $libros): static { $this->libros = $libros; return $this; } public function getTipoFirma(): ?string { return $this->tipo_firma; } public function setTipoFirma(string $tipo_firma): static { $this->tipo_firma = $tipo_firma; return $this; } public function getFechaPresentacion(): ?\DateTimeInterface { return $this->fecha_presentacion; } public function setFechaPresentacion(\DateTimeInterface $fecha_presentacion): static { $this->fecha_presentacion = $fecha_presentacion; return $this; } public function getIdLocalidadAmbito(): ?int { return $this->id_localidad_ambito; } public function setIdLocalidadAmbito(int $id_localidad_ambito): static { $this->id_localidad_ambito = $id_localidad_ambito; return $this; } public function getIdAutoProvisorio(): ?int { return $this->id_auto_provisorio; } public function setIdAutoProvisorio(int $id_auto_provisorio): static { $this->id_auto_provisorio = $id_auto_provisorio; return $this; } public function getNotificacionAutoprovisorio(): ?\DateTimeInterface { return $this->notificacion_auto_provisorio; } public function setNotificacionAuto_provisorio(\DateTimeInterface $notificacion_auto_provisorio): static { $this->notificacion_auto_provisorio = $notificacion_auto_provisorio; return $this; } public function getPublicacionBoletinOficial(): ?\DateTimeInterface { return $this->publicacion_boletin_oficial; } public function setPublicacionBoletinOficial(\DateTimeInterface $publicacion_boletin_oficial): static { $this->publicacion_boletin_oficial = $publicacion_boletin_oficial; return $this; } public function getIdAutoDefinitivo(): ?int { return $this->id_auto_definitivo; } public function setIdAutoDefinitivo(int $id_auto_definitivo): static { $this->id_auto_definitivo = $id_auto_definitivo; return $this; } public function getNotificacionAutoDefinitivo(): ?\DateTimeInterface { return $this->notificacion_auto_definitivo; } public function setNotificacionAutoDefinitivo(\DateTimeInterface $notificacion_auto_definitivo): static { $this->notificacion_auto_definitivo = $notificacion_auto_definitivo; return $this; } public function getIdAutoCaducidad(): ?int { return $this->id_auto_caducidad; } public function setIdAutoCaducidad(int $id_auto_caducidad): static { $this->id_auto_caducidad = $id_auto_caducidad; return $this; } public function getObservacionCaducidad(): ?string { return $this->observacion_caducidad; } public function setObservacionCaducidad(string $observacion_caducidad): static { $this->observacion_caducidad = $observacion_caducidad; return $this; } public function getIdExpediente(): ?int { return $this->id_expediente; } public function setIdExpediente(int $id_expediente): static { $this->id_expediente = $id_expediente; return $this; } public function getRenuevaInterna(): ?int { return $this->renueva_interna; } public function setRenuevaInterna(int $renueva_interna): static { $this->renueva_interna = $renueva_interna; return $this; } public function getIdExtincion(): ?int { return $this->id_extincion; } public function setIdExtincion(int $id_extincion): static { $this->id_extincion = $id_extincion; return $this; } public function getCodigoPostal(): ?int { return $this->codigo_postal; } public function setCodigoPostal(int $codigo_postal): static { $this->codigo_postal = $codigo_postal; return $this; } public function getAnioExpElectronico(): ?int { return $this->anio_exp_electronico; } public function setAnioExpElectronico(int $anio_exp_electronico): static { $this->anio_exp_electronico = $anio_exp_electronico; return $this; } public function getNroExpElectronico(): ?int { return $this->nro_exp_electronico; } public function setNroExpElectronico(int $nro_exp_electronico): static { $this->nro_exp_electronico = $nro_exp_electronico; return $this; } public function getCuilApoderadoNotif(): ?string { return $this->cuil_apoderado_notif; } public function setCuilApoderadoNotif(string $cuil_apoderado_notif): static { $this->cuil_apoderado_notif = $cuil_apoderado_notif; return $this; } } 自动驾驶: <?php namespace App\Entity; use App\Repository\AutoridadRepository; use Doctrine\DBAL\Types\Types; use Doctrine\ORM\Mapping as ORM; #[ORM\Entity(repositoryClass: AutoridadRepository::class)] class Autoridad { #[ORM\Id] #[ORM\GeneratedValue] #[ORM\Column] private ?int $id = null; #[ORM\Column] private ?int $documento = null; #[ORM\Column(length: 1)] private ?string $sexo = null; #[ORM\Column(length: 10)] private ?string $tipo = null; #[ORM\Column(length: 200)] private ?string $apellido_nombre = null; #[ORM\Column(length: 100)] private ?string $apellido = null; #[ORM\Column(length: 100)] private ?string $nombre = null; #[ORM\Column(length: 100)] private ?string $domicilio = null; #[ORM\Column(length: 50)] private ?string $telefono = null; #[ORM\Column(length: 100)] private ?string $correo = null; #[ORM\Column(type: Types::DATE_MUTABLE)] private ?\DateTimeInterface $fecha_alta = null; #[ORM\Column(type: Types::DATE_MUTABLE)] private ?\DateTimeInterface $fecha_baja = null; #[ORM\Column] private ?int $id_rol = null; #[ORM\Column] private ?int $orden = null; #[ORM\Column] private ?int $id_partido = null; #[ORM\Column] private ?int $id_eleccion_interna = null; #[ORM\Column] private ?int $id_alianza = null; public function getId(): ?int { return $this->id; } public function getApellidoNombre(): ?string { return $this->apellido_nombre; } public function getDocumento(): ?int { return $this->documento; } public function setDocumento(int $documento): static { $this->documento = $documento; return $this; } public function getSexo(): ?string { return $this->sexo; } public function setSexo(string $sexo): static { $this->sexo = $sexo; return $this; } public function getTipo(): ?string { return $this->tipo; } public function setTipo(string $tipo): static { $this->tipo = $tipo; return $this; } public function getApellido_Nombre(): ?string { return $this->apellido_nombre; } public function setApellido_Nombre(string $apellido_nombre): static { $this->apellido_nombre = $apellido_nombre; return $this; } public function getApellido(): ?string { return $this->apellido; } public function setApellido(string $apellido): static { $this->apellido = $apellido; return $this; } public function getNombre(): ?string { return $this->nombre; } public function setNombre(string $nombre): static { $this->nombre = $nombre; return $this; } public function getDomicilio(): ?string { return $this->domicilio; } public function setDomicilio(string $domicilio): static { $this->domicilio = $domicilio; return $this; } public function getTelefono(): ?string { return $this->telefono; } public function setTelefono(string $telefono): static { $this->telefono = $telefono; return $this; } public function getCorreo(): ?string { return $this->correo; } public function setCorreo(string $correo): static { $this->correo = $correo; return $this; } public function getFechaAlta(): ?\DateTimeInterface { return $this->fecha_alta; } public function setFechaAlta(\DateTimeInterface $fecha_alta): static { $this->fecha_alta = $fecha_alta; return $this; } public function getFechaBaja(): ?\DateTimeInterface { return $this->fecha_baja; } public function setFechaBaja(\DateTimeInterface $fecha_baja): static { $this->fecha_baja = $fecha_baja; return $this; } public function getIdRol(): ?int { return $this->id_rol; } public function setIdRol(int $id_rol): static { $this->id_rol = $id_rol; return $this; } public function getOrden(): ?int { return $this->orden; } public function setOrden(int $orden): static { $this->orden = $orden; return $this; } public function getIdPartido(): ?int { return $this->id_partido; } public function setIdPartido(int $id_partido): static { $this->id_partido = $id_partido; return $this; } public function getIdEleccionInterna(): ?int { return $this->id_eleccion_interna; } public function setIdEleccionInterna(int $id_eleccion_interna): static { $this->id_eleccion_interna = $id_eleccion_interna; return $this; } public function getIdAlianza(): ?int { return $this->id_alianza; } public function setIdAlianza(int $id_alianza): static { $this->id_alianza = $id_alianza; return $this; } } 我试图通过尝试choiceType的不同选项以及尝试entityType来解决问题: ->add('id_autoridad', EntityType::class, [ 'class' => Autoridad::class, 'query_builder' => function (EntityRepository $er) use ($id_partido) { return $er->createQueryBuilder('a') ->andWhere('a.id_partido = :id_partido') ->setParameter('id_partido', $id_partido); }, 'choice_label' => function (Autoridad $autoridad) { if(strlen($autoridad->getApellido_Nombre())> 0){ return $autoridad->getApellido_Nombre(); }elseif(strlen($autoridad->getNombre())> 0){ return $autoridad->getNombre() ." ".$autoridad->getApellido(); }else{ return $autoridad->getId(); } }, 'choice_value' => function (?Autoridad $autoridad) { if ($autoridad !== null) { echo("<script>console.log('idAutoridad: " . $autoridad->getId() ."');</script>"); $value = (int) $autoridad->getId(); return $value; } echo("<script>console.log(' No Entro');</script>"); return ''; }, 'placeholder' => 'Selecciona un estado','required' => true, ]) 您的实体期望 $id_autoridad 为 int,但在形式上您正在使用选择对象的 EntityType

回答 1 投票 0

Symfony 表单:所选选项无效

我的symfony应用程序有这个实体: 我的 symfony 应用程序有这个 实体: <?php namespace App\Entity; class Lead { private ?string $zipCode; private ?string $city; public function getZipCode(): ?string { return $this->zipCode; } public function setZipCode(string $zipCode): self { $this->zipCode = $zipCode; return $this; } public function getCity(): ?string { return $this->city; } public function setCity(string $city): self { $this->city = $city; return $this; } } 表格LeadType是: $builder->add('zipCode', TextType::class, [ 'attr' => [ 'placeholder' => 'Ex : 44000', 'onchange' => 'cityChoices(this.value)', ] ]) ->add('city', ChoiceType::class, [ 'choices' => [], 'attr' => ['class' => 'form-control'], 'choice_attr' => function () {return ['style' => 'color: #010101;'];}, ]); 当用户输入邮政编码时,javascript函数cityChoices()使用外部API添加选择选项,例如: 我的问题是控制器中的表单无效。因为用户选择了 LeadType 的选项中未提供的城市('choices' => [])。 这是错误: 0 => Symfony\Component\Form\FormError {#3703 ▼ #messageTemplate: "The selected choice is invalid." #messageParameters: array:1 [▼ "{{ value }}" => "Bar-le-Duc" ] 如何使选择有效? 完全@craight 我添加到表格中: ->addEventListener(FormEvents::PRE_SUBMIT, function(FormEvent$event){ $form = $event->getForm(); $city = $event->getData()['city']; if($city){ $form->add('city', ChoiceType::class, ['choices' => [$city => $city]]); } }) 预提交时,我更新选择并仅让用户选择'choices' => ['Bar-le-Duc' => 'Bar-le-Duc'], 表单在控制器中生效 另一个答案,当将 EntityType 与之前可用但不再可用的实体(例如,软删除或过期)一起使用时,是使用自定义数据转换器在验证之前过滤发布的结果。 请参阅如何使用数据转换器 @ Symfony 文档。 在下面的(非功能性)示例中,EntityType(或ChoiceType)的自定义数据转换器根据给定自定义过滤器的数据库查询结果删除无效值: <?php /** * Transformer for collection of CustomerType objects. * * @implements DataTransformerInterface<Collection<array-key,string>,Collection<array-key,string>> */ class EntityCollectionTransformer implements DataTransformerInterface { protected ?Builder $queryBuilder = null; /** * The valid DeliveryPackOption::id for the current context. * * @var string[] */ protected ?array $validIds = null; /** * Constructor, injects the repository. */ public function __construct( protected readonly EntityRepository $repository ) { } /** * Get the query builder, to apply custom filters. */ public function getQueryBuilder(): Builder { // Reset the query builder $this->queryBuilder = $this->repository->getQueryBuilder(); // Reset the valid ids $this->validIds = null; return $this->queryBuilder; } /** * Get the valid DeliveryPackOption Ids for the current context. * * @return string[] */ public function getValidIds(): array { if (null !== $this->validIds) { return $this->validIds; } if (null === $this->queryBuilder) { $message = sprintf('You must call getQueryBuilder() before calling using %s.', self::class); throw new \LogicException($message); } /** @var Collection<array-key,Entity> */ $results = $this->queryBuilder->getQuery()->execute(); // Get the valid ids from the database $this->validIds = array_map( fn (Entity $option): string => $option->getId(), $results->toArray(), ); return $this->validIds; } /** * Check that the given Entity::id are available as choices for the current context. * * Prevent "invalid" choices to be submitted. * * @param Collection<array-key,string>|null $value * * @return Collection<array-key,string> */ #[\Override] public function transform(mixed $value): Collection { if (!$value instanceof Collection || 0 === $value->count()) { return new ArrayCollection(); } return new ArrayCollection(array_filter( $value->toArray(), fn (string $id): bool => in_array($id, $this->getValidIds(), true) )); } /** * Transform a Entity:id array to its corresponding ArrayCollection of Document. * * @param Collection<array-key,string>|null $value * * @return Collection<array-key,string>|null */ #[\Override] public function reverseTransform(mixed $value): ?Collection { return $value; } } 并在表单中,获取变压器服务,并设置自定义查询过滤器: <?php class FormType extends AbstractType { protected ?EntityTransformer $entityTransformer = null; /** * Set the DeliveryPackOptionReferenceCollectionTransformer service, used for dependency injection. */ #[Required] public function setEntityTransformer( EntityTransformer $entityTransformer ): void { $this->entityTransformer = $entityTransformer; } public function buildForm(FormBuilderInterface $builder, array $options): void { if (!$this->entityTransformer instanceof EntityTransformer) { throw new \RuntimeException('EntityTransformer service is not set.'); } // Prepare the Entity collection filtering transformer query builder $qb = $this->entityTransformer->getQueryBuilder(); $qb->andWhere('deleted = :false'); ->setParameter('false', false); $builder ->add('city', EntityType::class, [ 'class' => Entity::class, ]) ; $builder->get('delivery.deliveryPackOptions') ->addModelTransformer($this->entityTransformer); } }

回答 2 投票 0

具有选择形式的 Symfony DataTransformers

我制作了一个 DataTransformer,它基本上不是针对提交的可用选择。 我的问题是我的变压器收到 ['INFO' => 'INFO', 'WARN' => 'WARN'] 或 ...

回答 1 投票 0

将多个项目分配给一个类别 - 一对多关系

我想将许多项目分配给一个类别。我正在使用 Symfony 2.6.7。 我不属于这里的所有者。如果我打开这个 URI: /类别/2/分配 [x] 项目 1 [x] 项目 2 (保存按钮) 我有

回答 1 投票 0

Symfony 表单 - 自定义按钮类型无法读取属性

我正在 Symfony 5.4 中使用 Symfony Form,我需要以下内容: 我有一个具有一些属性的 DTO。在我们的应用程序中,默认的 ButtonType 在主题树枝中有一些特殊的处理(特别是...

回答 2 投票 0

我们是否迁移错误?从 Symfony 2.7 迁移到 4.0 的表单中未发生验证

在从 Symfony 2.7 迁移到 4.0 的代码中,我的表单上不再进行验证,从而允许错误数据通过并导致违反 Doctrine 约束 我是 Symfony 的新手,被要求...

回答 1 投票 0

动态选择类型(select2 + AJAX)

我需要一个表单字段来从数千个实体中进行选择,因此像 select2 (使用 AJAX)这样的动态选择系统非常适合。 我的 AJAX 端点工作正常,但自定义表单类型不行...

回答 1 投票 0

是否可以在configureOptions中动态设置data_class?

我正在尝试重构一些糟糕的代码,目前我有超过 20 个表单(字典),其中一个名为 name 的字段,以及两个带有额外字段的类似表单(字典)。 这些表格正在嵌入...

回答 1 投票 0

验证动态填充的选择字段

我有两个选择字段,一个取决于另一个。 构建表单时,依赖字段得到一个空的选项数组。 然后,我在 JavaScript 中填写此字段,请求来自...的一些数据

回答 1 投票 0

Symfony 表单管理 OneToManyToOne 关系(带有额外字段的ManyToMany)

也许你们中的一些人可以帮助我? 我正在努力构建我正在构建的表单。在我的应用程序中,用户可以创建名为“家庭”的群组并邀请其他用户加入该家庭。我想创造...

回答 1 投票 0

Symfony2 数据转换器、验证器和错误消息

我问了这个问题,发现我们无法获取DataTransformer抛出的错误消息(根据唯一回答的用户的说法,也许有可能,我不知道)。 无论如何,现在我...

回答 1 投票 0

© www.soinside.com 2019 - 2024. All rights reserved.