【问题标题】:How could I achieve sending emails in Symfony2/SwiftMailer service with the following criteria?如何使用以下标准在 Symfony2/SwiftMailer 服务中发送电子邮件?
【发布时间】:2015-07-11 01:11:50
【问题描述】:

我正在努力完成一项令我丧命的任务! 我只能在没有成功的情况下回复一个丑陋的消息! 看看下面我的两个简单类....他们通过我的应用程序中的表单假装发送电子邮件,根据通过提到的表单(产品和城市)插入的两个标准来选择我的数据库中的人员。

这个错误的可能原因应该是什么:

 An exception occurred while executing 'SELECT u0_.email AS email0 FROM userInfo u0_ WHERE u0_.city = ? AND u0_.products = ? LIMIT 1' with params [{}, {}]:
Catchable Fatal Error: Object of class Quotera\EmailBundle\Entity\Email could not be converted to string  

    public function EmailAction(Request $request){
        $email = new Email();

        $form = $this->createForm(new EmailType());
        if ($request->isMethod('POST')) {
            $form->submit($request);

            if ($form->isValid()) {

     $city = $email->setCity($form->get('city')->getData());       
     $product =$email->setProduct($form->get('product')->getData());

                $user = $this->getUser();
                $email->setOwner($user);
                $email->setName($user);
                $email->setCity($form->get('city')->getData());
                $email->setProduct($form->get('product')->getData());
                $email->setMessage($form->get('message')->getData());
                $email->setEmail("exellent@sometoon.com");          
                $email->setEmailTo($this->sendEmailsToProviders($city, $product));
                $email->setTime($form->get('time')->getData());
                $em = $this->getDoctrine()->getManager();
                $em->persist($email);
                $em->flush();
                $message = \Swift_Message::newInstance()
                    ->setSubject($form->get('product')->getData())
                    ->setFrom('exellent@sometoon.com')
                    ->setTo($this->sendEmailsToProviders($city,$product))
                    ->setCharset('utf-8')
                    ->setContentType('text/html')
                    ->setBody('Thank you', 'text/html');
                $this->get('mailer')->send($message);
                $request->getSession()->getFlashBag()->add('success', 'Your quotation has been sent' );

            }
        }
        return array(
            'form' => $form->createView()
        );

    }

    public function sendEmailsToProviders($city, $product)
    {
        $em = $this->getDoctrine ()->getManager();
        $qb = $em->createQueryBuilder();

        $emails = $qb->select('u')->from('UserBundle:userInfo', 'u')
            ->select('u.email')
            ->andWhere('u.city = :city')
            ->setParameter('city', $city)
            ->andWhere('u.product = :product')
            ->setParameter('product',  $product  )
            ->setMaxResults(5)
            ->getQuery()
            ->execute();


        if(!$emails){
           throw new NotFoundHttpException('Sorry, no Providers with that criteria!');
        }
        return $emails; }





If I  var_dump($this->sendEmailsToProviders('Berlin','Butter' )) ; I get this result

array (size=5)
  0 => 
    array (size=1)
      'email' => string 'iancasillasbuffon@gmail.com' (length=27)
  1 => 
    array (size=1)
      'email' => string 'iancasillasbuffon@gmail.com' (length=27)
  2 => 
    array (size=1)
      'email' => string 'eddynvg@hotmail.com' (length=19)
  3 => 
    array (size=1)
      'email' => string 'dolphin23@dolphin.net' (length=21)
  4 => 
    array (size=1)
      'email' => string 'dolphin@dolphin.org' (length=19) 


     <?php

namespace Quotera\EmailBundle\Entity;

use Doctrine\ORM\Mapping as ORM;
//use Gedmo\Mapping\Annotation as Gedmo;
use Symfony\Component\Validator\Constraints as Assert;
use Symfony\Component\HttpFoundation\File\UploadedFile;
use Quotera\UserBundle\Entity\User;



   /**
    * Email
    *
    * @ORM\Table(name="quottum_email")
    * @ORM\Entity(repositoryClass="Quotera\EmailBundle\Repository\EmailRepository")
    * @ORM\HasLifecycleCallbacks
    *
    */
    class Email
    {
/**
 * @var integer
 *
 * @ORM\Column(name="id", type="integer")
 * @ORM\Id
 * @ORM\GeneratedValue(strategy="AUTO")
 */
private $id;

/**
 * @ORM\ManyToOne(targetEntity="Quotera\UserBundle\Entity\User")
 * @ORM\JoinColumn(onDelete="CASCADE")
 */
private $owner;

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

/**
 * @var integer
 *
 * @ORM\Column(name="tracking", type="integer")
 */
private $tracking;

/**
 * @ORM\Column(type="string")
 */
private $ip;

/**
 * @var string
 *
 * @ORM\Column(name="quotation_sender", type="string", length=255)
 */
private $quotationSender;

/**
 * @var string
 *
 * @ORM\Column(name="product", type="string", length=255)
 */
private $product;

/**
 * @var string
 *
 * @ORM\Column(name="city", type="string", length=255)
 */
private $city;

/**
 * @var string
 *
 * @ORM\Column(name="category", type="string", length=255)
 */
private $category;

/**
 * @var string
 *
 * @ORM\Column(name="message", type="string", length=255)
 */
private $message;

/**
 * @var integer
 *
 * @ORM\Column(name="message_id", type="integer")
 */
private $messageId;

/**
 * @var integer
 *
 * @ORM\Column(name="quantity", type="integer")
 */
private $quantity;

/**
 * @var string
 *
 * @ORM\Column(name="qty_type", type="string", length=255)
 */
private $qtyType;

/**
 * @var string
 *
 * @ORM\Column(name="username", type="string", length=255)
 */
private $username;

private $temp;

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

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

/**
 * @var string
 *
 * @ORM\Column(name="email_to", type="string", length=255)
 */
private $emailTo;

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


/**
 * @Assert\File(maxSize="6000000")
 */
private $file;

/**
 * @var \DateTime
 *
 * @ORM\Column(name="time", type="date", nullable=true)
 */
private $time;


/**
 * Get id
 *
 * @return integer
 */
public function getId()
{
    return $this->id;
}

/**
 * @param User $owner
 */
public function setOwner(User $owner)
{
    $this->owner = $owner;
}

/**
 * @return User
 */
public function getOwner()
{
    return $this->owner;
}


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

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



/**
 * Set tracking
 *
 * @param integer $tracking
 * @return Email
 */
public function setTracking($tracking)
{
    $this->tracking = $tracking;

    return $this;
}

/**
 * Get tracking
 *
 * @return integer
 */
public function getTracking()
{
    return $this->tracking;
}

/**
 * Set quotationSender
 *
 * @param string $quotationSender
 * @return Email
 */
public function setQuotationSender($quotationSender)
{
    $this->quotationSender = $quotationSender;

    return $this;
}

/**
 * Get quotationSender
 *
 * @return string
 */
public function getQuotationSender()
{
    return $this->quotationSender;
}

/**
 * Set product
 *
 * @param string $product
 * @return Email
 */
public function setProduct($product)
{
    $this->product = $product;

    return $this;
}

/**
 * Get product
 *
 * @return string
 */
public function getProduct()
{
    return $this->product;
}

/**
 * Set city
 *
 * @param string $city
 * @return Email
 */
public function setCity($city)
{
    $this->city = $city;

    return $this;
}

/**
 * Get city
 *
 * @return string
 */
public function getCity()
{
    return $this->city;
}

/**
 * Set category
 *
 * @param string $category
 * @return Email
 */
public function setCategory($category)
{
    $this->category = $category;

    return $this;
}

/**
 * Get category
 *
 * @return string
 */
public function getCategory()
{
    return $this->category;
}

/**
 * Set message
 *
 * @param string $message
 * @return Email
 */
public function setMessage($message)
{
    $this->message = $message;

    return $this;
}

/**
 * Get message
 *
 * @return string
 */
public function getMessage()
{
    return $this->message;
}

/**
 * Set messageId
 *
 * @param integer $messageId
 * @return Email
 */
public function setMessageId($messageId)
{
    $this->messageId = $messageId;

    return $this;
}

/**
 * Get messageId
 *
 * @return integer
 */
public function getMessageId()
{
    return $this->messageId;
}

/**
 * Set quantity
 *
 * @param integer $quantity
 * @return Email
 */
public function setQuantity($quantity)
{
    $this->quantity = $quantity;

    return $this;
}

/**
 * Get quantity
 *
 * @return integer
 */
public function getQuantity()
{
    return $this->quantity;
}

/**
 * Set qtyType
 *
 * @param string $qtyType
 * @return Email
 */
public function setQtyType($qtyType)
{
    $this->qtyType = $qtyType;

    return $this;
}

/**
 * Get qtyType
 *
 * @return string
 */
public function getQtyType()
{
    return $this->qtyType;
}

/**
 * Set username
 *
 * @param string $username
 * @return Email
 */
public function setUsername($username)
{
    $this->username = $username;

    return $this;
}

/**
 * Get username
 *
 * @return string
 */
public function getUsername()
{
    return $this->username;
}

/**
 * Set image
 *
 * @param string $image
 * @return Email
 */
public function setImage($image)
{
    $this->image = $image;

    return $this;
}

/**
 * Get image
 *
 * @return string
 */
public function getImage()
{
    return $this->image;
}

/**
 * Set email
 *
 * @param string $email
 * @return Email
 */
public function setEmail($email)
{
    $this->email = $email;

    return $this;
}

/**
 * Get email
 *
 * @return string
 */
public function getEmail()
{
    return $this->email;
}

/**
 * Set emailTo
 *
 * @param string $emailTo
 * @return Email
 */
public function setEmailTo($emailTo)
{
    $this->emailTo = $emailTo;

    return $this;
}

/**
 * Get emailTo
 *
 * @return string
 */
public function getEmailTo()
{
    return $this->emailTo;
}

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

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

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

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

/**
 * @ORM\Column(type="string", length=255, nullable=true)
 */
private  $path;


public function getWebPath()
{
    return null === $this->path
        ? null
        : $this->getUploadDir().'/'.$this->path;
}

protected function getUploadRootDir()
{
    // the absolute directory path where uploaded
    // documents should be saved
    return __DIR__.'/../../../../web/'.$this->getUploadDir();
}

protected function getUploadDir()
{
    // get rid of the __DIR__ so it doesn't screw up
    // when displaying uploaded doc/image in the view.
    return 'images/products';
}

/**
 * Sets file.
 *
 * @param UploadedFile $file

public function setFile(UploadedFile $file = null)
{
$this->file = $file;
// check if we have an old image path
if (isset($this->path)) {
// store the old name to delete after the update
$this->temp = $this->path;
$this->path = null;
} else {
$this->path = 'initial';
}
}
 */
/**
 * Sets file.
 *
 * @param UploadedFile $file
 */
public function setFile(UploadedFile $file = null)
{
    $this->file = $file;
    // check if we have an old image path
    if (isset($this->path)) {
        // store the old name to delete after the update
        $this->temp = $this->path;
        $this->path = null;
    } else {
        $this->path = 'initial';
    }
}

/**
 * @ORM\PrePersist()
 * @ORM\PreUpdate()
 */
public function preUpload()
{
    if (null !== $this->getFile()) {
        $this->path = $this->getFile()->guessExtension();
    }
}
/**
 * Get file.
 *
 * @return UploadedFile
 */
public function getFile()
{
    return $this->file;
}

/**
 * @ORM\PostPersist()
 * @ORM\PostUpdate()
 */
/**
 * @ORM\PostPersist()
 * @ORM\PostUpdate()
 */
public function upload()
{
    if (null === $this->getFile()) {
        return;
    }

    // check if we have an old image
    if (isset($this->temp)) {
        // delete the old image
        unlink($this->temp);
        // clear the temp image path
        $this->temp = null;
    }

    // you must throw an exception here if the file cannot be moved
    // so that the entity is not persisted to the database
    // which the UploadedFile move() method does
    $this->getFile()->move(
        $this->getUploadRootDir(),
        $this->id.'.'.$this->getFile()->guessExtension()
    );

    $this->setFile(null);
}

/**
 * @ORM\PreRemove()
 */
public function storeFilenameForRemove()
{
    $this->temp = $this->getAbsolutePath();
}

/**
 * @ORM\PostRemove()
 */
public function removeUpload()
{
    if (isset($this->temp)) {
        unlink($this->temp);
    }
}

public function getAbsolutePath()
{
    return null === $this->path
        ? null
        : $this->getUploadRootDir().'/'.$this->id.'.'.$this->path;
}

/**
 * @param \DateTime $time
 */
public function setTime($time)
{
    $this->time = $time;
}

/**
 * @return \DateTime
 */
public function getTime()
{
    return $this->time;
}





/**
 * Set path
 *
 * @param string $path
 *
 * @return Email
 */
public function setPath($path)
{
    $this->path = $path;

    return $this;
}

/**
 * Get path
 *
 * @return string
 */
public function getPath()
{
    return $this->path;
  }
}

希望那些天才中的一位能将光明带回我的道路! 感谢并提前祝福!

【问题讨论】:

    标签: php email symfony swiftmailer doctrine-query


    【解决方案1】:

    如果 $city 和 $product 是字符串而不是类或数组,请使用 dump() 检查。

       $city = $email->setCity($form->get('city')->getData());       
       $product =$email->setProduct($form->get('product')->getData());
    

    也许需要这样

      $city = $form->get('city')->getData();       
      $product =$form->get('product')->getData();
    
      $email->setCity($city);       
      $email->setProduct($product);
    

    【讨论】:

    • 似乎它越来越接近解决方案,但现在我得到了这个新错误:注意:数组到字符串的转换。日志中更详细:CRITICAL - Uncaught PHP Exception Symfony\Component\Debug\Exception\ContextErrorException: "Notice: Array to string conversion" at C:\wamp\www\Quotera\vendor\doctrine\dbal\lib\Doctrine\DBAL \Statement.php 第 120 行
    • 如果你有 symfony >2.3 最好使用 $form->handleRequest($request);表单有效后的 dump($email) 也许你不需要像 $form->get('city')->getData() 那样第二次设置所有变量。也许乳清已经在 $email 中了。您的错误似乎 $city 或 $product 不是字符串而是数组。显示电子邮件实体或 $city 和 $product 变量的转储。
    • 在我提交表单后,我从 var_dump($email) 中返回:private 'product' => string '衬衫、裤子、鞋子、内衣' (length=31) private 'city' => string 'Berlin' (length=6) ...但这就是挑战!在属性 'emailTo' 中,是一个空数组:(见下文) private 'emailTo' => array (size=3) 0 => array (size=1) 'email' => array (size=1) 1 =>数组 (size=1) 'email' => 数组 (size=1) 2 => 数组 (size=1) 'email' => 数组 (size=1)
    • 并且错误信息是Notice: Array to string conversion
    • 很难帮助,发布您的 EMAIL 实体,然后我可以说出实体想要字符串而不是数组的位置。据我所知:$city 和 $product 是字符串,$emails 是数组(),函数 sendEmailsToProviders () return array(), $email->setEmailTo() 都是字符串,那么你想在 $email->setEmailTo() 字符串中如何设置 return sendEmailsToProviders() ?
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2023-03-08
    • 2013-12-29
    • 2017-08-05
    • 1970-01-01
    • 2015-05-05
    • 2020-01-12
    • 2012-10-09
    相关资源
    最近更新 更多