繁体   English   中英

Symfony4复选框不保存

[英]Symfony4 checkbox doesn't save

我需要在ManyToOne和另一个Entity(Property)中基于一个Entity(Equipment)做一个复选框。 我做了复选框,但是有一个问题:我没有任何错误消息,但是我的添加/编辑没有保存选中/未选中的复选框。 我已经在这里整理过: https ://symfony.com/doc/current/reference/forms/types/entity.html,我也在Google上剪了一下,但我不明白问题出在哪里(所以我找不到解决方案)。 这是我的代码:

<?php

namespace App\Entity;

use Doctrine\Common\Collections\ArrayCollection;
use Doctrine\Common\Collections\Collection;
use Doctrine\ORM\Mapping as ORM;
use Symfony\Component\Validator\Constraints as Assert;

/**
 * @ORM\Entity(repositoryClass="App\Repository\PropertyRepository")
 */
class Property
{
    /**
     * @ORM\Id()
     * @ORM\GeneratedValue()
     * @ORM\Column(type="integer")
     * @Assert\Type("integer")
     */
    private $id;

/**
 * @ORM\Column(type="string", length=255)
 * @Assert\NotBlank
 * @Assert\Choice({"Appartement", "Maison", "Garage", "Bureau", "Château", "Commerce"})
 */
private $propertyCategory;

/**
 * @ORM\Column(type="string", length=255)
 * @Assert\NotBlank
 * @Assert\Type("string")
 */
private $uniqueName;

/**
 * @ORM\Column(type="string", length=255)
 * @Assert\NotBlank
 * @Assert\Type("string")
 */
private $address;

/**
 * @ORM\Column(type="string", length=255)
 * @Assert\NotBlank
 * @Assert\Type("string")
 */
private $city;

/**
 * @ORM\Column(type="integer")
 * @Assert\NotBlank
 * @Assert\Type("integer")
 * @Assert\Length(min = 5, minMessage = "Ce champ doit contenir 5 chiffres")
 * @Assert\Length(max = 5, maxMessage = "Ce champ doit contenir 5 chiffres")
 */
private $zipCode;

/**
 * @ORM\Column(type="string", length=255)
 * @Assert\NotBlank
 * @Assert\Country
 */
private $country;

/**
 * @ORM\Column(type="integer")
 * @Assert\NotBlank
 * @Assert\Type("integer")
 */
private $surfaceInSquareMeter;

/**
 * @ORM\Column(type="integer")
 * @Assert\NotBlank
 * @Assert\Type("integer")
 */
private $numberOfPiece;

/**
 * @ORM\Column(type="text", nullable=true)
 * @Assert\Type("string")
 */
private $description;

/**
 * @ORM\Column(type="string", length=255)
 * @Assert\NotBlank
 * @Assert\Choice({"Meublé", "Non neublé"})
 */
private $rentalCategory;

/**
 * @ORM\Column(type="float")
 * @Assert\NotBlank
 * @Assert\Type("float")
 */
private $rentExcludingCharges;

/**
 * @ORM\Column(type="float")
 * @Assert\NotBlank
 * @Assert\Type("float")
 */
private $charges;

/**
 * @ORM\Column(type="float")
 * @Assert\NotBlank
 * @Assert\Type("float")
 */
private $purchasePrice;

/**
 * @ORM\ManyToOne(targetEntity="App\Entity\User", inversedBy="properties")
 */
private $userProperty;

/**
 * @ORM\OneToMany(targetEntity="App\Entity\Equipment", mappedBy="equipment")
 */
private $equipments;

public function __construct()
{
    $this->equipments = new ArrayCollection();
}

public function getId(): ?int
{
    return $this->id;
}

public function getPropertyCategory(): ?string
{
    return $this->propertyCategory;
}

public function setPropertyCategory(string $propertyCategory): self
{
    $this->propertyCategory = $propertyCategory;

    return $this;
}

public function getUniqueName(): ?string
{
    return $this->uniqueName;
}

public function setUniqueName(string $uniqueName): self
{
    $this->uniqueName = $uniqueName;

    return $this;
}

public function getAddress(): ?string
{
    return $this->address;
}

public function setAddress(string $address): self
{
    $this->address = $address;

    return $this;
}

public function getCity(): ?string
{
    return $this->city;
}

public function setCity(string $city): self
{
    $this->city = $city;

    return $this;
}

public function getZipCode(): ?int
{
    return $this->zipCode;
}

public function setZipCode(int $zipCode): self
{
    $this->zipCode = $zipCode;

    return $this;
}

public function getCountry(): ?string
{
    return $this->country;
}

public function setCountry(string $country): self
{
    $this->country = $country;

    return $this;
}

public function getSurfaceInSquareMeter(): ?int
{
    return $this->surfaceInSquareMeter;
}

public function setSurfaceInSquareMeter(int $surfaceInSquareMeter): self
{
    $this->surfaceInSquareMeter = $surfaceInSquareMeter;

    return $this;
}

public function getNumberOfPiece(): ?int
{
    return $this->numberOfPiece;
}

public function setNumberOfPiece(int $numberOfPiece): self
{
    $this->numberOfPiece = $numberOfPiece;

    return $this;
}

public function getDescription(): ?string
{
    return $this->description;
}

public function setDescription(?string $description): self
{
    $this->description = $description;

    return $this;
}

public function getRentalCategory(): ?string
{
    return $this->rentalCategory;
}

public function setRentalCategory(string $rentalCategory): self
{
    $this->rentalCategory = $rentalCategory;

    return $this;
}

public function getRentExcludingCharges(): ?float
{
    return $this->rentExcludingCharges;
}

public function setRentExcludingCharges(float $rentExcludingCharges): self
{
    $this->rentExcludingCharges = $rentExcludingCharges;

    return $this;
}

public function getCharges(): ?float
{
    return $this->charges;
}

public function setCharges(float $charges): self
{
    $this->charges = $charges;

    return $this;
}

public function getPurchasePrice(): ?float
{
    return $this->purchasePrice;
}

public function setPurchasePrice(float $purchasePrice): self
{
    $this->purchasePrice = $purchasePrice;

    return $this;
}

public function getUserProperty(): ?User
{
    return $this->userProperty;
}

public function setUserProperty(?User $userProperty): self
{
    $this->userProperty = $userProperty;

    return $this;
}

/**
 * @return Collection|Equipment[]
 */
public function getEquipments(): Collection
{
    return $this->equipments;
}

public function addEquipment(Equipment $equipment): self
{
    if (!$this->equipments->contains($equipment)) {
        $this->equipments[] = $equipment;
        $equipment->setEquipment($this);
    }

    return $this;
}

public function removeEquipment(Equipment $equipment): self
{
    if ($this->equipments->contains($equipment)) {
        $this->equipments->removeElement($equipment);
        // set the owning side to null (unless already changed)
        if ($equipment->getEquipment() === $this) {
            $equipment->setEquipment(null);
        }
    }

    return $this;
}
}

这是我的设备实体,我将设备放在属性名称的数据库中

<?php

namespace App\Entity;

use Doctrine\ORM\Mapping as ORM;
use Symfony\Component\Validator\Constraints as Assert;

/**
 * @ORM\Entity(repositoryClass="App\Repository\EquipmentRepository")
 */
class Equipment
{
    /**
     * @ORM\Id()
     * @ORM\GeneratedValue()
     * @ORM\Column(type="integer")
     * @Assert\Type("integer")
     */
    private $id;

    /**
     * @ORM\Column(type="string", nullable=true)
     * @Assert\Type("string")
     */
    private $name;

    /**
     * @ORM\ManyToOne(targetEntity="App\Entity\Property", inversedBy="equipments")
     */
    private $equipment;

    /**
     * @return mixed
     */
    public function getId(): ?int
    {
        return $this->id;
    }

    /**
     * @param mixed $id
     */
    public function setId($id): int
    {
        $this->id = $id;
    }

    /**
     * @return mixed
     */
    public function getName(): ?string
    {
        return $this->name;
    }

    /**
     * @param mixed $name
     */
    public function setName($name): string
    {
        $this->name = $name;
    }

    public function getEquipment(): ?Property
    {
        return $this->equipment;
    }

    public function setEquipment(?Property $equipment): self
    {
        $this->equipment = $equipment;

        return $this;
    }
}

这是表格:

<?php

namespace App\Form;

use App\Entity\Equipment;
use App\Entity\Property;
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\CountryType;
use Symfony\Component\Form\Extension\Core\Type\IntegerType;
use Symfony\Component\Form\Extension\Core\Type\NumberType;
use Symfony\Component\Form\Extension\Core\Type\TextType;
use Symfony\Component\Form\FormBuilderInterface;
use Symfony\Component\OptionsResolver\OptionsResolver;

class PropertyType extends AbstractType
{
    /**
     * @param FormBuilderInterface $builder
     * @param array $options
     */
    public function buildForm(FormBuilderInterface $builder, array $options)
    {
        $builder
            ->add('propertyCategory', ChoiceType::class, [
                'required' => true,
                'choices' => [
                    'Appartement' => 'Appartement',
                    'Maison' => 'Maison',
                    'Garage' => 'Garage',
                    'Bureau' => 'Bureau',
                    'Château' => 'Château',
                    'Commerce' => 'Commerce',
                ],
                'label' => 'Type de bien'
            ])
            ->add('uniqueName', TextType::class, ['required' => true, 'label' => 'Nom unique'])
            ->add('address', TextType::class, ['required' => true, 'label' => 'Adresse'])
            ->add('city', TextType::class, ['required' => true, 'label' => 'Ville'])
            ->add('zipCode', IntegerType::class, ['required' => true, 'label' => 'Code postal'])
            ->add('country', CountryType::class, ['required' => true, 'label' => 'Pays'])
            ->add('surfaceInSquareMeter', IntegerType::class, [
                'required' => true,
                'label' => 'Surface en m²'
            ])
            ->add('numberOfPiece', IntegerType::class, ['required' => true, 'label' => 'Nombre de pièces'])
            ->add('description', TextType::class, ['required' => false, 'label' => 'Description'])
            ->add('equipments', EntityType::class, [
                'required' => false,
                'label' => 'Equipements',
                'class' => Equipment::class,
                'multiple' => true,
                'expanded' => true,
                'choice_label' => 'name',
            ])
            ->add('rentalCategory', ChoiceType::class, [
                'required' => true,
                'choices' => [
                    'Meublé' => 'Meublé',
                    'Non meublé' => 'Non meublé',
                ],
                'label' => 'Type de location'
            ])
            ->add('rentExcludingCharges', NumberType::class, [
                'required' => true,
                'label' => 'Loyer hors charges'
            ])
            ->add('charges', NumberType::class, ['required' => true, 'label' => 'Charges'])
            ->add('purchasePrice', NumberType::class, ['required' => true, 'label' => 'Prix d\'achat'])
//            ->add('userProperty')
        ;
    }

    /**
     * @param OptionsResolver $resolver
     */
    public function configureOptions(OptionsResolver $resolver)
    {
        $resolver->setDefaults([
            'data_class' => Property::class,
        ]);
    }
}

我的控制器在这里

<?php

namespace App\Controller;

use App\Entity\Property;
use App\Form\PropertyType;
use App\Repository\PropertyRepository;
use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\Routing\Annotation\Route;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\IsGranted;

/**
 * @Route("/proprietes")
 * @IsGranted("ROLE_USER")
 */
class PropertyController extends AbstractController
{
    /**
     * @Route("/", name="property_index", methods={"GET"})
     * @param PropertyRepository $propertyRepository
     * @return Response
     */
    public function index(PropertyRepository $propertyRepository): Response
    {
        return $this->render('property/index.html.twig', [
            'properties' => $propertyRepository->findAll(),
        ]);
    }

    /**
     * @Route("/new", name="property_new", methods={"GET","POST"})
     * @param Request $request
     * @return Response
     */
    public function new(Request $request): Response
    {
        $property = new Property();
        $form = $this->createForm(PropertyType::class, $property);
        $form->handleRequest($request);

        if ($form->isSubmitted() && $form->isValid()) {
            $entityManager = $this->getDoctrine()->getManager();
            $entityManager->persist($property);
            $entityManager->flush();

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

        return $this->render('property/new.html.twig', [
            'property' => $property,
            'form' => $form->createView(),
        ]);
    }

    /**
     * @Route("/{id}", name="property_show", methods={"GET"})
     * @param Property $property
     * @return Response
     */
    public function show(Property $property): Response
    {
        return $this->render('property/show.html.twig', [
            'property' => $property,
        ]);
    }

    /**
     * @Route("/{id}/edit", name="property_edit", methods={"GET","POST"})
     * @param Request $request
     * @param Property $property
     * @return Response
     */
    public function edit(Request $request, Property $property): Response
    {
        $form = $this->createForm(PropertyType::class, $property);
        $form->handleRequest($request);

        if ($form->isSubmitted() && $form->isValid()) {
            $this->getDoctrine()->getManager()->flush();

            return $this->redirectToRoute('property_index', [
                'id' => $property->getId(),
            ]);
        }

        return $this->render('property/edit.html.twig', [
            'property' => $property,
            'form' => $form->createView(),
        ]);
    }

    /**
     * @Route("/{id}", name="property_delete", methods={"DELETE"})
     * @param Request $request
     * @param Property $property
     * @return Response
     */
    public function delete(Request $request, Property $property): Response
    {
        if ($this->isCsrfTokenValid('delete'.$property->getId(), $request->request->get('_token'))) {
            $entityManager = $this->getDoctrine()->getManager();
            $entityManager->remove($property);
            $entityManager->flush();
        }

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

我的表演视图:

{% extends 'layout.html.twig' %}

{% block title %}Propriétées{% endblock %}

{% block body %}
    <a href="{{ path('property_index') }}"><i class="fas fa-long-arrow-alt-left"></i> Revenir à la liste</a>

    <h1>Propriétée</h1>

    <table class="table">
        <tbody>
            <tr>
                <th>Type de bien</th>
                <td>{{ property.propertyCategory }}</td>
            </tr>
            <tr>
                <th>Nom</th>
                <td>{{ property.uniqueName }}</td>
            </tr>
            <tr>
                <th>Adresse</th>
                <td>{{ property.address }}</td>
            </tr>
            <tr>
                <th>Ville</th>
                <td>{{ property.city }}</td>
            </tr>
            <tr>
                <th>Code postal</th>
                <td>{{ property.zipCode }}</td>
            </tr>
            <tr>
                <th>Pays</th>
                <td>{{ property.country }}</td>
            </tr>
            <tr>
                <th>Surface en m²</th>
                <td>{{ property.surfaceInSquareMeter }}</td>
            </tr>
            <tr>
                <th>Nombre de pièces</th>
                <td>{{ property.numberOfPiece }}</td>
            </tr>
            <tr>
                <th>Description</th>
                <td>{{ property.description }}</td>
            </tr>
            <tr>
                <th>Equipement</th>
                    {% for equipment in property %}
                        <td>{{ property.equipments }}</td>
                    {% endfor %}
            </tr>
            <tr>
                <th>Type de location</th>
                <td>{{ property.rentalCategory }}</td>
            </tr>
            <tr>
                <th>Loyer hors charges</th>
                <td>{{ property.rentExcludingCharges }}</td>
            </tr>
            <tr>
                <th>Charges</th>
                <td>{{ property.charges }}</td>
            </tr>
            <tr>
                <th>Prix d'achat</th>
                <td>{{ property.purchasePrice }}</td>
            </tr>
        </tbody>
    </table>

    <a href="{{ path('property_edit', {'id': property.id}) }}"><i class="fas fa-edit"></i> éditer</a>

    {{ include('property/_delete_form.html.twig') }}
{% endblock %}

希望你能帮助我,谢谢!

我认为您在equipments字段上缺少by_reference => false属性。

编辑:在您的show.html.twig中尝试

{% for equipment in property %}
    <td>{{ equipment.name }}</td>
{% endfor %}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM