我担心我的实体对于ManyToOne单向关系的持久性。实际上,我有一个链接到 ticket 实体的 Order 实体,在订购单中,我可以选择票据。 这是命令实体中的外键
/**
* @ORM\Entity(repositoryClass="App\Repository\CommandRepository")
*/
class Command
{
….
/**
* @ORM\ManyToOne(targetEntity="App\Entity\Ticket")
* @ORM\JoinColumn(nullable=false, name="Ticket_id", referencedColumnName="id")
*/
private $ticket;
...
CommandForm的生成器是
public function buildForm(FormBuilderInterface $builder, array $options)
{
$builder->add('datevisite', DateType::class,['widget' => 'choice',
'format' => 'dd-MM-yyyy', 'html5' => false,'label'=>'Date de la visite', 'attr'=>['class' => 'js-datepicker'] ])
->add('ticket', EntityType::class,['required'=>true, 'class' => Ticket::class,'choice_label'=>'nombillet', 'attr'=>['placeholder'=>'Choisissez le type de billet']])
->add('email', EmailType::class,['required'=>true, 'label'=>'Votre mail', 'attr'=>['placeholder'=>'Entrez votre adresse mail ']])
;
当我使用
保存(持久)命令时$manager->persist($command);
$manager->flush();
自动将新的故障单创建并分配给命令,而不是使用下拉列表中的选定故障单注册命令。
请帮助我仅使用现有票证的外键保留Command(选定) 谢谢
答案 0 :(得分:0)
我的控制器
<?php
namespace App\Controller;
use App\Entity\Command;
use App\Notification\NotificationContact;
use App\Entity\Typebillet;
use App\Entity\Typetarif;
use App\Entity\Visiteur;
use App\Form\Type\CommandType;
use App\Module\Module;
use Doctrine\Common\Collections\ArrayCollection;
use Symfony\Component\HttpFoundation\Session\SessionInterface;
use Symfony\Bridge\Doctrine\Form\Type\EntityType;
use Doctrine\Common\Persistence\ObjectManager;
use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
use Symfony\Component\Routing\Annotation\Route;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\Form\Extension\Core\Type\TextType;
use Symfony\Component\Form\Extension\Core\Type\DateType;
use Symfony\Component\Form\Extension\Core\Type\SubmitType;
use Symfony\Component\Form\Extension\Core\Type\NumberType;
use Symfony\Component\Form\Extension\Core\Type\CheckboxType;
use Symfony\Component\Form\Extension\Core\Type\ChoiceType;
use Symfony\Component\Form\Extension\Core\Type\CountryType;
use Symfony\Component\Form\Extension\Core\Type\EmailType;
class LouvreController extends AbstractController
{
private $lacommand ;
private $session;
public function __construct()
{
$this->lacommand = new Command();
}
/**
* @Route("/billet/reservation", name="louvre_billet")
*/
public function billet(Request $request, SessionInterface $session){
// $this->lacommand = new command();
//$form = $this->createFormBuilder($command)
$form = $this->createForm(CommandType::class, $this->lacommand);
$form->handleRequest($request);
if ($form->isSubmitted() && $form->isValid()) {
$this->lacommand->setDatecommande(new \DateTime());
$today = new \DateTime();
if ( Module::CommandeJourPasse($this->lacommand->getDatevisite()) == -1 ) {
return $this->rediriger('danger', 'Attention vous ne pouvez commander un billet pour un jour passé!!!', 'louvre_billet');
}
if ( Module::AuDela14H($this->lacommand->getTypebillet()->getId(), $this->lacommand->getDatevisite() ) == -1 ) {
return $this->rediriger('danger', 'Attention vous ne pouvez commander un billet journée au delà de 14 le jour même', 'louvre_billet');
}
if ( $this->recherchetarif($this->lacommand) === -1) {
$this->addFlash('danger', 'Attention vous devez enregistrer au moins un visiteur ' );
return $this->redirectToRoute('louvre_billet', array(), 301);
}
$nbrebilletDuJourDeVisite = $this->getDoctrine()
->getRepository(Command::class)
->sumNumberVisite( $this->lacommand->getDatevisite()->format('Y-m-d') );
if (($nbrebilletDuJourDeVisite + $this->lacommand->getNombrebillet()) > 1000) {
$dispo = 1000 - $nbrebilletDuJourDeVisite;
$this->addFlash('danger', 'Attention votre commande ne peut être effectuée, car la capacité d\' accueil journalière est limitée à 1000 visites. Actuellemnt '.$dispo.' billet(s) disponible(s)' );
return $this->redirectToRoute('louvre_billet', array(), 301);
}
$verif = $this->verifJourOuvrables($this->lacommand->getDatevisite());
if($verif['error'] >0) {
$this->addFlash('danger', $verif['message'] );
return $this->redirectToRoute('louvre_billet', array(), 301);
}
$session->set('command', $this->lacommand);
return $this->paie($this->lacommand);
}
return $this->render('louvre/resa.html.twig', array(
'formCommand' => $form->createView(),
));
}
public function paie(Command $command){
return $this->render('louvre/paiement.html.twig', [
'datevisite'=> $command->getDatevisite()->format('d-M-Y'),
'nombrebillet' => $command->getNombrebillet(),
'montantnet' => $command->getMontantnet(),
'email' => $command->getEmail() ,
'command'=>$command] );
}
/**
* @Route("/billet/paiement", name="le_paiement")
*/
public function paiement( Request $request, ObjectManager $manager, SessionInterface $session , \Swift_Mailer $mailer){
if ($request->request->get('stripeToken') !== null) {
$command = $session->get('command');
/* dump($command);
die();*/
$montantnetCent = $command->getMontantnet() * 100;
try{
// Set your secret key: remember to change this to your live secret key in production
// See your keys here: https://dashboard.stripe.com/account/apikeys
\Stripe\Stripe::setApiKey("sk_test_0thjJ32tl0y6X8kc5Wdz0XSt");
// Token is created using Checkout or Elements!
// Get the payment token ID submitted by the form:
$token = $request->request->get('stripeToken');
$charge = \Stripe\Charge::create([
'amount' => $montantnetCent,
'currency' => 'eur',
'description' => 'Achat billet musée de Louvre -- '.$command->getEmail(),
'source' => $token,
]);
}
catch (Exception $e) {
$error = $e->getMessage();
$this->addFlash('danger', $error );
return $this->redirectToRoute('louvre_billet', array(), 301);
}
/**
* ici on va générer et insérer le code
*/
$code = $command->getDatevisite()->format('ymd')."-".substr($command->getTypebillet()->getNombillet(),0,4)."-".uniqid();
$command->setCode($code);
$manager->persist($command);
$manager->flush($command);
/**
* envoie de mail
*/
$message = (new \Swift_Message('Musée de LOUVRE : Votre reservation '))
->setFrom('louvre@museelouvre.com')
->setTo($command->getEmail())
->setBody(
$this->renderView(
// templates/emails/registration.html.twig
'emails/mail.html.twig',
array('datevisite' => $command->getDatevisite(),
'typebillet' => $command->getTypebillet()->getNombillet(),
'montantnet' => $command->getMontantnet(),
'visiteurs' => $command->getVisiteurs(),
'code' => $command-> getCode(),
)
),
'text/html'
);
$mailer->send($message);
dump($mailer->send($message));
/**
* fin envoie
*/
return $this->render(
// templates/emails/registration.html.twig
'emails/mail.html.twig',
array('datevisite' => $command->getDatevisite(),
'typebillet' => $command->getTypebillet()->getNombillet(),
'montantnet' => $command->getMontantnet(),
'visiteurs' => $command->getVisiteurs(),
'code' => $command->getCode()
));
/*$this->addFlash('success', 'Paiement effectué avec succes ' );
return $this->redirectToRoute('louvre_billet', array(), 301); */
}
else{
$this->addFlash('danger', 'Un probleme est survenu lors du paiement ' );
return $this->redirectToRoute('louvre_billet', array(), 301);
}
}
public function recherchetarif(Command $command){
$tarif = new Typetarif();
$today = new \DateTime();
$reduction = 0;
$montantbrut = 0;
$lesvisiteurs= new ArrayCollection();
$manager = $this->getDoctrine()->getManager();
if ($command->getVisiteurs()->count() == 0) {
return -1;
}
foreach ($command->getVisiteurs() as $visiteur) {
# code...
/**
* On calcule l'age de chaque visiteur et on recupère le tarif correspondant
*/
$datenais = $visiteur->getDatenaissance()->format('Y-m-d');
$datenais = new \DateTime($datenais);
$age = date_diff($today, $datenais);
$tarif = $this->getDoctrine()
->getRepository(Typetarif::class)
->findCostByAge($age->y);
// $command->removeVisiteur($visiteur);
$visiteur->setTypetarif($tarif);
$montantbrut = $montantbrut + $tarif->getTarifmontant();
$lesvisiteurs->add($visiteur);
//$manager->persist($visiteur->getTypetarif());
}
// on calcul le montant brut de la facture brut = PUBillet x Nbre de billet
//$montantbrut = $tarif->getTarifmontant() * $command->getNombrebillet();
$command->setMontantbrut ($montantbrut);
$command->setNombrebillet($command->getVisiteurs()->count());
// On impute une éventuelle reduction de 10 euros
if ( $command->getTarifreduit()==true) {
$reduction = 10;
}
$command->setMontantreduit($reduction);
// on applique le montant net = montant brut - reduction
$command->setMontantnet($montantbrut - $reduction);
return 0;
}
public function verifJourOuvrables($datevisite)
{ $error = 0;
$message = '';
if ($datevisite->format('N') == 2) {
$error = $error + 1;
$message = 'Désolé le musée n\' pas oiuvert le Mardi !!!';
return ['error'=>$error, 'message'=>$message];
}
if ($datevisite->format('j') == 1 and $datevisite->format('m')==5) {
$error = $error + 1;
$message = 'Désolé le musée n\' ouvre pas le 1er MAI !!!';
return ['error'=>$error, 'message'=>$message];
}
if ($datevisite->format('j') == 1 and $datevisite->format('m')==11) {
$error = $error + 1;
$message = 'Désolé le musée n\' ouvre pas le 1er Novembre !!!';
return ['error'=>$error, 'message'=>$message];
}
if ($datevisite->format('j') == 25 and $datevisite->format('m')==12) {
$error = $error + 1;
$message = 'Désolé le musée n\' ouvre pas le 25 Decembre !!!';
return ['error'=>$error, 'message'=>$message];
}
}
public function rediriger($type, $message, $route){
$this->addFlash($type , $message );
return $this->redirectToRoute($route, array(), 301);
}
}
在此Controller中,用于保留所有实体的函数是
/**
* @Route("/billet/paiement", name="le_paiement")
*/
public function paiement( Request $request, ObjectManager $manager, SessionInterface $session , \Swift_Mailer $mailer){
if ($request->request->get('stripeToken') !== null) {
$command = $session->get('command');
/* dump($command);
die();*/
$montantnetCent = $command->getMontantnet() * 100;
try{
// Set your secret key: remember to change this to your live secret key in production
// See your keys here: https://dashboard.stripe.com/account/apikeys
\Stripe\Stripe::setApiKey("sk_test_0thjJ32tl0y6X8kc5Wdz0XSt");
// Token is created using Checkout or Elements!
// Get the payment token ID submitted by the form:
$token = $request->request->get('stripeToken');
$charge = \Stripe\Charge::create([
'amount' => $montantnetCent,
'currency' => 'eur',
'description' => 'Achat billet musée de Louvre -- '.$command->getEmail(),
'source' => $token,
]);
}
catch (Exception $e) {
$error = $e->getMessage();
$this->addFlash('danger', $error );
return $this->redirectToRoute('louvre_billet', array(), 301);
}
/**
* ici on va générer et insérer le code
*/
$code = $command->getDatevisite()->format('ymd')."-".substr($command->getTypebillet()->getNombillet(),0,4)."-".uniqid();
$command->setCode($code);
$manager->persist($command);
$manager->flush($command);
/**
* envoie de mail
*/
$message = (new \Swift_Message('Musée de LOUVRE : Votre reservation '))
->setFrom('louvre@museelouvre.com')
->setTo($command->getEmail())
->setBody(
$this->renderView(
// templates/emails/registration.html.twig
'emails/mail.html.twig',
array('datevisite' => $command->getDatevisite(),
'typebillet' => $command->getTypebillet()->getNombillet(),
'montantnet' => $command->getMontantnet(),
'visiteurs' => $command->getVisiteurs(),
'code' => $command-> getCode(),
)
),
'text/html'
);
$mailer->send($message);
dump($mailer->send($message));
/**
* fin envoie
*/
return $this->render(
// templates/emails/registration.html.twig
'emails/mail.html.twig',
array('datevisite' => $command->getDatevisite(),
'typebillet' => $command->getTypebillet()->getNombillet(),
'montantnet' => $command->getMontantnet(),
'visiteurs' => $command->getVisiteurs(),
'code' => $command->getCode()
));
/*$this->addFlash('success', 'Paiement effectué avec succes ' );
return $this->redirectToRoute('louvre_billet', array(), 301); */
}
else{
$this->addFlash('danger', 'Un probleme est survenu lors du paiement ' );
return $this->redirectToRoute('louvre_billet', array(), 301);
}
}
谢谢