我需要根据ManyToOne中的实体(设备(与另一个实体(属性(进行复选框。我做了复选框,但有一个问题:我没有任何错误消息,但我的添加/编辑没有保存选中/未选中的复选框。我已经在这里徘徊了:https://symfony.com/doc/current/reference/forms/types/entity.html,我也在谷歌上徘徊,但我不明白问题出在哪里(所以我找不到解决方案(。这是我的代码:
<?php
namespace AppEntity;
use DoctrineCommonCollectionsArrayCollection;
use DoctrineCommonCollectionsCollection;
use DoctrineORMMapping as ORM;
use SymfonyComponentValidatorConstraints as Assert;
/**
* @ORMEntity(repositoryClass="AppRepositoryPropertyRepository")
*/
class Property
{
/**
* @ORMId()
* @ORMGeneratedValue()
* @ORMColumn(type="integer")
* @AssertType("integer")
*/
private $id;
/**
* @ORMColumn(type="string", length=255)
* @AssertNotBlank
* @AssertChoice({"Appartement", "Maison", "Garage", "Bureau", "Château", "Commerce"})
*/
private $propertyCategory;
/**
* @ORMColumn(type="string", length=255)
* @AssertNotBlank
* @AssertType("string")
*/
private $uniqueName;
/**
* @ORMColumn(type="string", length=255)
* @AssertNotBlank
* @AssertType("string")
*/
private $address;
/**
* @ORMColumn(type="string", length=255)
* @AssertNotBlank
* @AssertType("string")
*/
private $city;
/**
* @ORMColumn(type="integer")
* @AssertNotBlank
* @AssertType("integer")
* @AssertLength(min = 5, minMessage = "Ce champ doit contenir 5 chiffres")
* @AssertLength(max = 5, maxMessage = "Ce champ doit contenir 5 chiffres")
*/
private $zipCode;
/**
* @ORMColumn(type="string", length=255)
* @AssertNotBlank
* @AssertCountry
*/
private $country;
/**
* @ORMColumn(type="integer")
* @AssertNotBlank
* @AssertType("integer")
*/
private $surfaceInSquareMeter;
/**
* @ORMColumn(type="integer")
* @AssertNotBlank
* @AssertType("integer")
*/
private $numberOfPiece;
/**
* @ORMColumn(type="text", nullable=true)
* @AssertType("string")
*/
private $description;
/**
* @ORMColumn(type="string", length=255)
* @AssertNotBlank
* @AssertChoice({"Meublé", "Non neublé"})
*/
private $rentalCategory;
/**
* @ORMColumn(type="float")
* @AssertNotBlank
* @AssertType("float")
*/
private $rentExcludingCharges;
/**
* @ORMColumn(type="float")
* @AssertNotBlank
* @AssertType("float")
*/
private $charges;
/**
* @ORMColumn(type="float")
* @AssertNotBlank
* @AssertType("float")
*/
private $purchasePrice;
/**
* @ORMManyToOne(targetEntity="AppEntityUser", inversedBy="properties")
*/
private $userProperty;
/**
* @ORMOneToMany(targetEntity="AppEntityEquipment", 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 AppEntity;
use DoctrineORMMapping as ORM;
use SymfonyComponentValidatorConstraints as Assert;
/**
* @ORMEntity(repositoryClass="AppRepositoryEquipmentRepository")
*/
class Equipment
{
/**
* @ORMId()
* @ORMGeneratedValue()
* @ORMColumn(type="integer")
* @AssertType("integer")
*/
private $id;
/**
* @ORMColumn(type="string", nullable=true)
* @AssertType("string")
*/
private $name;
/**
* @ORMManyToOne(targetEntity="AppEntityProperty", 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 AppForm;
use AppEntityEquipment;
use AppEntityProperty;
use SymfonyBridgeDoctrineFormTypeEntityType;
use SymfonyComponentFormAbstractType;
use SymfonyComponentFormExtensionCoreTypeChoiceType;
use SymfonyComponentFormExtensionCoreTypeCountryType;
use SymfonyComponentFormExtensionCoreTypeIntegerType;
use SymfonyComponentFormExtensionCoreTypeNumberType;
use SymfonyComponentFormExtensionCoreTypeTextType;
use SymfonyComponentFormFormBuilderInterface;
use SymfonyComponentOptionsResolverOptionsResolver;
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 AppController;
use AppEntityProperty;
use AppFormPropertyType;
use AppRepositoryPropertyRepository;
use SymfonyBundleFrameworkBundleControllerAbstractController;
use SymfonyComponentHttpFoundationRequest;
use SymfonyComponentHttpFoundationResponse;
use SymfonyComponentRoutingAnnotationRoute;
use SensioBundleFrameworkExtraBundleConfigurationIsGranted;
/**
* @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
属性。
编辑:试试这个在你的节目.html.twig
{% for equipment in property %}
<td>{{ equipment.name }}</td>
{% endfor %}