dongying7847 2019-04-01 04:07
浏览 42

给定一个下拉项目,从数据库symfony提供相应的电子邮件

I am trying to dynamically choose a recipient from the database with a dropdown. I have a list of items which are the two elements Department1, Department2 which are two items of my dropdown.

For Department1 I have email1@email.com

For Department2 I have email2@email.com

If I choose Department1 in the dropdown, I want it to be sent to email1@email.com.

My form is like this:

firstname: StringType
lastname: StringType
email: EmailType
Departments: EntityType

I have two entities:

  • ContactForm
  • Department

The relation between this ContactForm entity and the Department entity is OneToMany.

I already tried using a Repository but couldn't get it to work, even created a custom DQL.

Tried accessing it with $form["Department"]["email"] But got the exception couldn't access String("")

My DQL Attempt I got the intented result with pure SQL but can't find it to work with Doctrine

public function fetchDepartmentName($value){

       return $this->createQueryBuilder('c')
            ->join('c.department', 'd')
            ->andWhere('d.id=:val')
            ->setParameter('val',$value)
            ->select('d.nom')
            ->getQuery()
            ->getResult()
        ;
    }

ContactFormController

namespace App\Controller;

use App\Form\ContactFormType;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Route;
use Swift_SmtpTransport;
use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
use Symfony\Component\HttpFoundation\Request;
use Doctrine\ORM\EntityManagerInterface;

class ContactFormController extends AbstractController
{
    public function SendMail(\Swift_Mailer $mailer, $form)
    {
        $message = (new \Swift_Message('Test email'))
            ->setFrom('email@gmail.com')
            ->setTo($department)
            ->setBody(
                $this->renderView(
                // templates/emails/registration.html.twig
                    'contactform/mail_contact.html.twig', [
                        'form' => $form
                    ]
                ),
                'text/html'
            )
        ;

        $mailer->send($message);
    }


    /**
     * @param EntityManagerInterface $em
     * @param Request $request
     * @return \Symfony\Component\HttpFoundation\Response
     * @Route("/contact")
     */
    public function new(EntityManagerInterface $em, Request $request)
    {
        $transport = (new Swift_SmtpTransport('smtp.gmail.com', 587, 'tls'))
            ->setUsername('Email')
            ->setPassword('Password')
        ;

        $mailer = new \Swift_Mailer($transport);

        $form = $this->createForm(ContactFormType::class);

        $form->handleRequest($request);
        if ($form->isSubmitted() && $form->isValid()) {
            $contactForm = $form->getData();

//            $repository = $this->getDoctrine()->getRepository(ContactForm::class);
//            $department= $repository->fetchDepartmentName($form->get('Department')->getName());

            $cf = $request->get($form->getName());

            $em->persist($contactForm);
            $em->flush();
            $this->SendMail($mailer, $cf);

            $this->addFlash('success', 'Successfully submitted !');


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

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

ContactFormType

namespace App\Form;

use App\Entity\Department;
use App\Entity\ContactForm;
use Symfony\Bridge\Doctrine\Form\Type\EntityType;
use Symfony\Component\Form\AbstractType;
use Symfony\Component\Form\Extension\Core\Type\EmailType;
use Symfony\Component\Form\Extension\Core\Type\TextareaType;
use Symfony\Component\Form\Extension\Core\Type\TextType;
use Symfony\Component\Form\FormBuilderInterface;
use Symfony\Component\OptionsResolver\OptionsResolver;

class ContactFormType extends AbstractType
{
    public function buildForm(FormBuilderInterface $builder, array $options)
    {
        $builder
            ->add('Firstname', TextType::class)
            ->add('Lastname', TextType::class)
            ->add('Email', EmailType::class)
            ->add('Message', TextareaType::class)
            ->add('Department', EntityType::class, [
                'class' => Department::class,
                'choice_label' => 'nom'
            ])
        ;
    }

    public function configureOptions(OptionsResolver $resolver)
    {
        $resolver->setDefaults([
            'data_class' => ContactForm::class
        ]);
    }
}

ContactForm

namespace App\Entity;

use Doctrine\Common\Collections\ArrayCollection;
use Doctrine\Common\Collections\Collection;
use Doctrine\ORM\Mapping as ORM;

/**
 * @ORM\Entity(repositoryClass="App\Repository\ContactFormRepository")
 */
class ContactForm
{
    private $id;

    /**
     * @ORM\Column(type="string", length=25)
     */
    private $firstName;

    /**
     * @ORM\Column(type="string", length=50)
     */
    private $lastName;

    /**
     * @ORM\Column(type="string", length=100)
     */
    private $email;

    /**
     * @ORM\Column(type="text")
     */
    private $message;

    /**
     * @ORM\OneToMany(targetEntity="App\Entity\Department", mappedBy="contactForm")
     */
    private $department;

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

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

    public function getFirstName(): ?string
    {
        return $this->firstName;
    }

    public function setFirstName(string $firstName): self
    {
        $this->firstName = $firstName;

        return $this;
    }

    public function getLastName(): ?string
    {
        return $this->lastName;
    }

    public function setLastName(string $lastName): self
    {
        $this->lastName = $lastName;

        return $this;
    }

    public function getEmail(): ?string
    {
        return $this->email;
    }

    public function setEmail(string $email): self
    {
        $this->email = $email;

        return $this;
    }

    public function getMessage(): ?string
    {
        return $this->message;
    }

    public function setMessage(string $message): self
    {
        $this->message = $message;

        return $this;
    }

    /**
     * @return Collection|Department[]
     */
    public function getDepartment(): Collection
    {
        return $this->department;
    }

    /**
     * @param mixed $department
     * @return ContactForm
     */
    public function setDepartment(Department $department): self
    {
        if (!$this->department->contains($department)) {
            $this->department[] = $department;
            $department->setContactForm($this);
    }

        return $this;
    }

    public function addDepartment(Department $department): self
    {
        if (!$this->department->contains($department)) {
            $this->department[] = $department;
            $department->setContactForm($this);
        }

        return $this;
    }

    public function removeDepartment(Department $department): self
    {
        if ($this->department->contains($department)) {
            $this->department->removeElement($department);
            // set the owning side to null (unless already changed)
            if ($department->getContactForm() === $this) {
                $department->setContactForm(null);
            }
        }

        return $this;
    }
}

The expected results is that it sends to the correct email given the department. Actually, I can't get the $department dynamically and feed it to my mailer.

EDIT :

I succeeded I used my DQL Function I made to fetch the Department email with it's id.

public function fetchDepartmentEmail($value)
    {

        return $this->createQueryBuilder('c')
            ->join('c.departement', 'd')
            ->andWhere('d.id=:val')
            ->setParameter('val', $value)
            ->select('d.email')
            ->getQuery()
            ->getResult();
    }

Added $departement parameter to pass to my SendMail function and use it in the setTo paremeter which now is :

 ->setTo($departement[0]["email"])

And added those lines in my controller

$repository = $this->getDoctrine()->getRepository(ContactForm::class);
$departement = $repository->fetchDepartmentEmail($cf["Departement"]);
  • 写回答

0条回答 默认 最新

    报告相同问题?

    悬赏问题

    • ¥30 这是哪个作者做的宝宝起名网站
    • ¥60 版本过低apk如何修改可以兼容新的安卓系统
    • ¥25 由IPR导致的DRIVER_POWER_STATE_FAILURE蓝屏
    • ¥50 有数据,怎么建立模型求影响全要素生产率的因素
    • ¥50 有数据,怎么用matlab求全要素生产率
    • ¥15 TI的insta-spin例程
    • ¥15 完成下列问题完成下列问题
    • ¥15 C#算法问题, 不知道怎么处理这个数据的转换
    • ¥15 YoloV5 第三方库的版本对照问题
    • ¥15 请完成下列相关问题!