创建时的 Symfony4 双实体

穆库姆

我正在创建一个简单的邮件程序。首先,您需要创建一个 MailTemplate(实体)。这存在一个主题、mailFrom 和一个消息。然后创建邮件:这分两步进行。首先,您选择要发送到的帐户和您的 MailTemplate。然后您重定向到另一条路线,在那里我设置了主题、消息和邮件来源,以便我可以调整内容。

当我发送(保存邮件)。它保存了邮件,但复制了我的 MailTemplate 并将 Mailtemplate 保存到。所以我收到了 1 封邮件和 2 个模板。

我的模板实体

<?php
/**
 * Created by PhpStorm.
 * User: david
 * Date: 26-6-2018
 * Time: 20:13
 */

namespace App\Project\MailBundle\Entity;

use App\Project\BaseBundle\Entity\BaseEntity;
use Doctrine\Common\Collections\ArrayCollection;
use Doctrine\Common\Collections\Collection;
use Symfony\Component\Validator\Constraints as Assert;
use Symfony\Bridge\Doctrine\Validator\Constraints\UniqueEntity;
use Doctrine\ORM\Mapping as ORM;

/**
 * Class MailTemplates
 * @package App\Project\MailBundle\Entity
 */

/**
 * @ORM\Entity(repositoryClass="App\Project\MailBundle\Repository\MailTemplatesRepository")
 */
class MailTemplate extends BaseEntity
{

    public function __construct()
    {
        parent::__construct();

        $this->active = true;
        $this->bulkmails = new ArrayCollection();
        $this->mails = new ArrayCollection();
    }

    /**
     * @var string $template
     *
     * @ORM\Column(name="template", type="string", length=191, nullable=false)
     *
     *
     */
    private $template;

    /**
     * @var string $mailFrom
     *
     * @ORM\Column(type="string", length=191, nullable=false, options={"default": "[email protected]"})
     * @Assert\NotBlank()
     *
     */
    private $mailFrom;

    /**
     * @var string $mailSubject
     *
     * @ORM\Column(type="string", length=191, nullable=false)
     * @Assert\NotBlank()
     *
     */
    private $mailSubject;

    /**
     * @var string $mailMessage
     *
     * @ORM\Column(type="text", nullable=false)
     * @Assert\NotBlank()
     *
     */
    private $mailMessage;

    /**
     * @ORM\OneToMany(targetEntity="App\Project\MailBundle\Entity\Mail", mappedBy="mailTemplate", orphanRemoval=true)
     */
    private $mails;

    /**
     * @ORM\OneToMany(targetEntity="App\Project\MailBundle\Entity\BulkMail", mappedBy="mailTemplate", orphanRemoval=true)
     */
    private $bulkmails;

    /**
     * @return string
     */
    public function getTemplate(): ? string
    {
        return $this->template;
    }

    /**
     * @param string $template
     */
    public function setTemplate(string $template): void
    {
        $this->template = $template;
    }

    /**
     * @return mixed
     */
    public function getMailFrom()
    {
        return $this->mailFrom;
    }

    /**
     * @param mixed $mailFrom
     */
    public function setMailFrom($mailFrom): void
    {
        $this->mailFrom = $mailFrom;
    }

    /**
     * @return mixed
     */
    public function getMailSubject()
    {
        return $this->mailSubject;
    }

    /**
     * @param mixed $mailSubject
     */
    public function setMailSubject($mailSubject): void
    {
        $this->mailSubject = $mailSubject;
    }

    /**
     * @return mixed
     */
    public function getMailMessage()
    {
        return $this->mailMessage;
    }

    /**
     * @param mixed $mailMessage
     */
    public function setMailMessage($mailMessage): void
    {
        $this->mailMessage = $mailMessage;
    }

    /**
     * @return mixed
     */
    public function getMails(): collection
    {
        return $this->mails;
    }

    /**
     * @param mixed $mails
     */
    public function setMails($mails)
    {
        $this->mails = $mails;
    }

    /**
     * @return mixed
     */
    public function getBulkmails(): collection
    {
        return $this->bulkmails;
    }

    /**
     * @param mixed $bulkmails
     */
    public function setBulkmails($bulkmails)
    {
        $this->bulkmails = $bulkmails;
    }



    public function __toString()
    {
        return $this->getTemplate();
    }

}

我的邮件实体

<?php
/**
 * Created by PhpStorm.
 * User: david
 * Date: 26-6-2018
 * Time: 20:13
 */

namespace App\Project\MailBundle\Entity;

use App\Project\BaseBundle\Entity\BaseEntity;
use Doctrine\Common\Collections\ArrayCollection;
use Symfony\Component\Validator\Constraints as Assert;
use Doctrine\ORM\Mapping as ORM;


/**
 * Class BulkMail
 * @package App\Project\MailBundle\Entity
 */

/**
 * @ORM\Entity(repositoryClass="App\Project\MailBundle\Repository\BulkMailRepository")
 */
class BulkMail extends BaseEntity
{

    public function __construct()
    {
        parent::__construct();

        $this->mailTo = new ArrayCollection();
        $this->active = true;

    }

    /**
     * @ORM\ManyToOne(targetEntity="App\Project\MailBundle\Entity\MailTemplate", inversedBy="mails", cascade={"persist", "remove"})
     * @ORM\JoinColumn(name="bulkMail_id", referencedColumnName="id", nullable=false)
     */
    private $mailTemplate;

    /**
     * @ORM\ManyToMany(targetEntity="App\Project\AccountBundle\Entity\Account")
     * @ORM\JoinColumn(name="account_id", referencedColumnName="id", nullable=false)
     * @Assert\NotBlank()
     */
    private $mailTo;

    /**
     * @var string $mailFrom
     *
     * @ORM\Column(type="string", length=191, nullable=true)
     *
     */
    private $mailFrom;

    /**
     * @var string $mailSubject
     *
     * @ORM\Column(type="string", length=191, nullable=true)
     *
     */
    private $mailSubject;

    /**
     * @var string $mailMessage
     *
     * @ORM\Column(type="text", nullable=true)
     *
     */
    private $mailMessage;


    /**
     * @return mixed
     */
    public function getMailTo()
    {
        return $this->mailTo;
    }

    /**
     * @param mixed $mailTo
     */
    public function setMailTo($mailTo): void
    {
        $this->mailTo = $mailTo;
    }

    /**
     * @return mixed
     */
    public function getMailFrom()
    {
        return $this->mailFrom;
    }

    /**
     * @param mixed $mailFrom
     */
    public function setMailFrom($mailFrom): void
    {
        $this->mailFrom = $mailFrom;
    }

    /**
     * @return mixed
     */
    public function getMailSubject()
    {
        return $this->mailSubject;
    }

    /**
     * @param mixed $mailSubject
     */
    public function setMailSubject($mailSubject): void
    {
        $this->mailSubject = $mailSubject;
    }

    /**
     * @return mixed
     */
    public function getMailMessage()
    {
        return $this->mailMessage;
    }

    /**
     * @param mixed $mailMessage
     */
    public function setMailMessage($mailMessage): void
    {
        $this->mailMessage = $mailMessage;
    }

    /**
     * @param mixed $accountId
     */
    public function setMail($account): void
    {
        $this->account = $account;
    }

    /**
     * @return mixed
     */
    public function getMailTemplate()
    {
        return $this->mailTemplate;
    }

    /**
     * @param mixed $mailTemplate
     */
    public function setMailTemplate($mailTemplate)
    {
        $this->mailTemplate = $mailTemplate;
    }

    public function __toString()
    {
        return $this->mailSubject;
    }
}

我的控制器

<?php
/**
 * Created by PhpStorm.
 * User: david
 * Date: 5-7-2018
 * Time: 22:41
 */

namespace App\Project\MailBundle\Controller;

use App\Project\AccountBundle\Entity\Account;
use App\Project\MailBundle\Entity\BulkMail;
use App\Project\MailBundle\Entity\MailTemplate;
use App\Project\MailBundle\Forms\BulkAddMailAdminType;
use App\Project\MailBundle\Forms\bulkSelectmailAdminType;
use App\Project\BaseBundle\Controller\BaseController;
use Symfony\Component\HttpFoundation\Request;


class BulkMailController extends BaseController
{
    public function BulkMailIndexAction()
    {
        $MailRepository = $this->getDoctrine()->getRepository(BulkMail::class);
        $items = $MailRepository->findAll();
        return $this->render('@ProjectMail/mails/bulk/index.html.twig', array(
            'items' => $items
        ));
    }

    public function bulkSelectAction(Request $request) {

        $mail = new BulkMail();

        $form = $this->createForm(BulkSelectmailAdminType::class, $mail);

        if ($request->getMethod() == 'POST') {

            $form->handleRequest($request);

            if ($form->isSubmitted() && $form->isValid()) {
                $TemplateRepository = $this->getDoctrine()->getRepository(MailTemplate::class);
                $tId = $mail->getMailTemplate()->getId();
                $template = $TemplateRepository->findOneBy(array('id' => $tId));
                $mail->setMailSubject($template->getMailSubject());
                $mail->setMailFrom($template->getMailFrom());
                $mail->setMailMessage($template->getMailMessage());
                $mail->setMailTemplate($template);

                $this->container->get('session')->set('Bmail', $mail);

                $response = $this->redirectToRoute('mailBulkSend');
                return $response;
            }
        }

        $label = "Email opmaken";
        $response = $this->render('@ProjectMail/mails/bulk/addBulk_select.html.twig', array(
            'form' => $form->createView(),
            'label' => $label
        ));

        return $response;

    }

    /**
     * @param Request $request
     * @param \Swift_Mailer $mailer
     * @return \Symfony\Component\HttpFoundation\RedirectResponse|\Symfony\Component\HttpFoundation\Response
     */
    public function bulkMailAction(Request $request, \Swift_Mailer $mailer) {

        $Bmail = $this->container->get('session')->get('Bmail');

            if ($Bmail) {
                $accounts = array();
                $AccountRepository = $this->getDoctrine()->getRepository(Account::class);

                $count = 0;

                foreach ($Bmail->getMailTo() as $key => $account) {
                    $accounts[] = $AccountRepository->findOneById($account->getId());
                    $count ++;
                }

                $form = $this->createForm(BulkAddMailAdminType::class, $Bmail);

                if ($request->getMethod() == 'POST') {

                    $form->handleRequest($request);

                    if ($form->isSubmitted() && $form->isValid()) {
                        $Bmail->setMailTo($accounts);

                        //dump($Bmail->getMailTemplate()); die;

                        $entityManager = $this->getDoctrine()->getManager();
                        $entityManager->persist($Bmail);
                        $entityManager->flush();

                        // Get account emails in array
                        foreach($accounts as $key => $acc){
                            $persons[$acc->getEmail()] = $acc->getEmail();
                        }


                        $message = (new \Swift_Message($Bmail->getMailSubject()))
                            ->setContentType("text/html")
                            ->setFrom($Bmail->getMailFrom())
                            ->setTo($persons)
                            ->setBody(
                                $this->renderView(
                                    '@ProjectTemplate/_templates/base_mail.html.twig', array(
                                        'type' => 'emailDefault',
                                        'template' => $Bmail
                                    )
                                )
                            )
                        ;
                       // $mailer->send($message);


                        $response = $this->redirectToRoute('mailsBulkList');
                        return $response;
                    }
                }

                $label = "Email verzenden";
                $response = $this->render('@ProjectMail/mails/bulk/addMail.html.twig', array(
                    'form' => $form->createView(),
                    'mail' => $Bmail,
                    'accounts' => $accounts,
                    'label' => $label
                ));

            } else {
                $response = $this->redirectToRoute('mailBulkAdd');
            }

        return $response;
    }

    public function deleteAction(BulkMail $mail)
    {
        $em = $this->getDoctrine()->getManager();
        $em->remove($mail);
        $em->flush();
        return $this->redirectToRoute('mailsBulkList');
    }
}

我不知道为什么会发生这种情况以及如何正确处理。建议?提前加油!!

穆库姆

感谢大佬的帮助,真的很感谢!

经过一些调试后,我得出了这个.. 不确定它是否应该是这样,但它可以工作.. 我在第一个动作中保存我的邮件并在我的会话中传递 id,在第二个动作中我通过邮件传递表单,(如果需要,可以进行更改)并发送(再次保存)。

做了一些清理:)

<?php
/**
 * Created by PhpStorm.
 * User: david
 * Date: 5-7-2018
 * Time: 22:41
 */

namespace App\Project\MailBundle\Controller;

use App\Project\AccountBundle\Entity\Account;
use App\Project\MailBundle\Entity\BulkMail;
use App\Project\MailBundle\Entity\MailTemplate;
use App\Project\MailBundle\Forms\BulkAddMailAdminType;
use App\Project\MailBundle\Forms\bulkSelectmailAdminType;
use App\Project\BaseBundle\Controller\BaseController;
use Symfony\Component\HttpFoundation\Request;


class BulkMailController extends BaseController
{
    public function BulkMailIndexAction()
    {
        $MailRepository = $this->getDoctrine()->getRepository(BulkMail::class);
        $items = $MailRepository->findAll();
        return $this->render('@ProjectMail/mails/bulk/index.html.twig', array(
            'items' => $items
        ));
    }

    public function bulkSelectAction(Request $request) {

        $mail = new BulkMail();

        $form = $this->createForm(BulkSelectmailAdminType::class, $mail);

        if ($request->getMethod() == 'POST') {

            $form->handleRequest($request);

            if ($form->isSubmitted() && $form->isValid()) {
                $entityManager = $this->getDoctrine()->getManager();
                $template = $mail->getMailTemplate();
                $mail->setMailSubject($template->getMailSubject());
                $mail->setMailFrom($template->getMailFrom());
                $mail->setMailMessage($template->getMailMessage());

                $entityManager->persist($mail);
                $entityManager->flush();
                $this->container->get('session')->set('Bmail', $mail->getId());

                $response = $this->redirectToRoute('mailBulkSend');
                return $response;
            }
        }

        $label = "Email opmaken";
        $response = $this->render('@ProjectMail/mails/bulk/addBulk_select.html.twig', array(
            'form' => $form->createView(),
            'label' => $label
        ));

        return $response;

    }

    /**
     * @param Request $request
     * @param \Swift_Mailer $mailer
     * @return \Symfony\Component\HttpFoundation\RedirectResponse|\Symfony\Component\HttpFoundation\Response
     */
    public function bulkMailAction(Request $request, \Swift_Mailer $mailer) {

        $BmailId = $this->container->get('session')->get('Bmail');

            if ($BmailId) {
                $entityManager = $this->getDoctrine()->getManager();
                $mailRepo = $this->getDoctrine()->getRepository(BulkMail::class);
                $Bmail = $mailRepo->find($BmailId);

                $accounts = array();
                $AccountRepository = $this->getDoctrine()->getRepository(Account::class);

                $count = 0;

                foreach ($Bmail->getMailTo() as $key => $account) {
                    $accounts[] = $AccountRepository->findOneById($account->getId());
                    $count ++;
                }

                $form = $this->createForm(BulkAddMailAdminType::class, $Bmail);

                if ($request->getMethod() == 'POST') {

                    $form->handleRequest($request);

                    if ($form->isSubmitted() && $form->isValid()) {
                        $Bmail->setMailTo($accounts);

                        $entityManager = $this->getDoctrine()->getManager();
                        $entityManager->persist($Bmail);
                        $entityManager->flush();

                        // Get account emails in array
                        foreach($accounts as $key => $acc){
                            $persons[$acc->getEmail()] = $acc->getEmail();
                        }

                        $message = (new \Swift_Message($Bmail->getMailSubject()))
                            ->setContentType("text/html")
                            ->setFrom($Bmail->getMailFrom())
                            ->setTo($persons)
                            ->setBody(
                                $this->renderView(
                                    '@ProjectTemplate/_templates/base_mail.html.twig', array(
                                        'type' => 'emailDefault',
                                        'template' => $Bmail
                                    )
                                )
                            )
                        ;
                       // $mailer->send($message);


                        $response = $this->redirectToRoute('mailsBulkList');
                        return $response;
                    }
                }

                $label = "Email verzenden";
                $response = $this->render('@ProjectMail/mails/bulk/addMail.html.twig', array(
                    'form' => $form->createView(),
                    'mail' => $Bmail,
                    'accounts' => $accounts,
                    'label' => $label
                ));

            } else {
                $response = $this->redirectToRoute('mailBulkAdd');
            }

        return $response;
    }

    public function deleteAction(BulkMail $mail)
    {
        $em = $this->getDoctrine()->getManager();
        $em->remove($mail);
        $em->flush();
        return $this->redirectToRoute('mailsBulkList');
    }
}

本文收集自互联网,转载请注明来源。

如有侵权,请联系[email protected] 删除。

编辑于
0

我来说两句

0条评论
登录后参与评论

相关文章

来自分类Dev

symfony4 如何使用实体关系创建 DataFixtures

来自分类Dev

Symfony4:如何从链接实体接收数据?

来自分类Dev

Symfony 4:创建添加实体表单时出错(@ParamConverter 注释找不到对象)

来自分类Dev

Symfony4学说单元测试:实体在缓存中是否有旧数据?

来自分类Dev

以 Symfony4 形式将实体对象值传递给嵌套的 CollectionTypes

来自分类Dev

在Symfony中使用主义创建实体时出错

来自分类Dev

如何从 Symfony 4 中的数组在实体中创建新条目?

来自分类Dev

为什么当我创建新实体时Shopify实体ID每次增加4?

来自分类Dev

当我尝试使用symfony创建实体时,出现中止的错误消息

来自分类Dev

symfony架构:在实体创建时具有存储库访问权限的自定义方法

来自分类Dev

安装 snappybundle symfony4

来自分类Dev

Symfony4:验证 DateIntervalType

来自分类Dev

Oracle ADF-在父实体创建时创建子实体

来自分类Dev

Symfony2从请求创建实体

来自分类Dev

Symfony从表单类型的实体中创建选择

来自分类Dev

在创建时未设置Breeze实体密钥

来自分类Dev

创建新实体时触发插件

来自分类Dev

在 Spring Java 中创建实体时出错

来自分类Dev

创建捆绑包时实体的良好实践

来自分类Dev

如果字段为空,则在嵌入表单中编辑父实体时删除子实体 - Symfony 4

来自分类Dev

更新实体时出错 - Symfony 3

来自分类Dev

在创建实体时将作者分配给实体

来自分类Dev

Symfony4 部署到共享主机

来自分类Dev

无法在 Symfony4 中注销用户

来自分类Dev

Symfony4 - isXmlHttpRequest 显示错误数据

来自分类Dev

树枝中的 Symfony4 翻译

来自分类Dev

PersistentCollection 中的 Symfony4 搜索

来自分类Dev

我们可以使用 KnpPaginatorBundle 在 Symfony 4 中创建基于 2 个实体的分页吗?

来自分类Dev

为几个实体创建表单symfony2.3(最佳实践)

Related 相关文章

  1. 1

    symfony4 如何使用实体关系创建 DataFixtures

  2. 2

    Symfony4:如何从链接实体接收数据?

  3. 3

    Symfony 4:创建添加实体表单时出错(@ParamConverter 注释找不到对象)

  4. 4

    Symfony4学说单元测试:实体在缓存中是否有旧数据?

  5. 5

    以 Symfony4 形式将实体对象值传递给嵌套的 CollectionTypes

  6. 6

    在Symfony中使用主义创建实体时出错

  7. 7

    如何从 Symfony 4 中的数组在实体中创建新条目?

  8. 8

    为什么当我创建新实体时Shopify实体ID每次增加4?

  9. 9

    当我尝试使用symfony创建实体时,出现中止的错误消息

  10. 10

    symfony架构:在实体创建时具有存储库访问权限的自定义方法

  11. 11

    安装 snappybundle symfony4

  12. 12

    Symfony4:验证 DateIntervalType

  13. 13

    Oracle ADF-在父实体创建时创建子实体

  14. 14

    Symfony2从请求创建实体

  15. 15

    Symfony从表单类型的实体中创建选择

  16. 16

    在创建时未设置Breeze实体密钥

  17. 17

    创建新实体时触发插件

  18. 18

    在 Spring Java 中创建实体时出错

  19. 19

    创建捆绑包时实体的良好实践

  20. 20

    如果字段为空,则在嵌入表单中编辑父实体时删除子实体 - Symfony 4

  21. 21

    更新实体时出错 - Symfony 3

  22. 22

    在创建实体时将作者分配给实体

  23. 23

    Symfony4 部署到共享主机

  24. 24

    无法在 Symfony4 中注销用户

  25. 25

    Symfony4 - isXmlHttpRequest 显示错误数据

  26. 26

    树枝中的 Symfony4 翻译

  27. 27

    PersistentCollection 中的 Symfony4 搜索

  28. 28

    我们可以使用 KnpPaginatorBundle 在 Symfony 4 中创建基于 2 个实体的分页吗?

  29. 29

    为几个实体创建表单symfony2.3(最佳实践)

热门标签

归档