2017-04-16 25 views
0

我試圖在用戶使用FOSUser Bundle進行註冊後添加默認配置文件圖片。但是,我不知道如何在我的__construct中添加這種文件,因爲它是一個需要的圖像映射實體。__construct()中的圖像類型文件

這裏是我的用戶實體:

<?php 
// src/AppBundle/Entity/User.php 

namespace AppBundle\Entity; 

use FOS\UserBundle\Model\User as BaseUser; 
use Doctrine\ORM\Mapping as ORM; 
use Symfony\Component\Validator\Constraints as Assert; 

/** 
* @ORM\Entity 
* @ORM\Table(name="fos_user") 
*/ 
class User extends BaseUser 
{ 
    /** 
    * @ORM\Id 
    * @ORM\Column(type="integer") 
    * @ORM\GeneratedValue(strategy="AUTO") 
    */ 
    protected $id; 

    /** 
    * @ORM\Column(type="string") 
    * 
    * @Assert\NotBlank(message="L'image doit être au format jpg") 
    * @Assert\File(maxSize = "100k",mimeTypes={ "image/jpg" }) 
    */ 
    private $image; 

    public function getImage() 
    { 
     return $this->image; 
    } 

    public function setImage($image) 
    { 
     $this->image = $image; 

     return $this; 
    } 

    public function __construct() 
    { 
     parent::__construct(); 
     // your own logic 
     $this->image = 'http://lorempixel.com/300/300/'; 
    } 
} 

我試着去適應:https://symfony.com/doc/current/controller/upload_file.html

+0

我沒有看到任何問題。請說明您遇到的問題,例如默認圖像是否未保存在數據庫中,還是不會顯示?你有什麼試圖找到問題?你的輸出或日​​志中是否有錯誤信息? – dbrumann

回答

0

下面一行 「$這個 - >圖像= 'http://lorempixel.com/300/300/';」 把一個字符串中的像場,當驗證器試圖使用「@Assert \ File(...)」驗證該字段時,它失敗了,因爲他找到了字符串而不是文件

您需要做的是將文件類型放入該字段像這樣:

use Symfony\Component\HttpFoundatio\File\UploadedFile; 

class User extends BaseUser 
..... 
    public function __construct() 
    { 
     parent::__construct(); 
     $this->image = new UploadedFile("http://lorempixel.com/300/300/", "defaultImg"); 
    } 
} 

第一個參數是路徑到您的文件,二是文件的名稱,檢查UploadedFile的類Symfony的API參考: http://api.symfony.com/2.3/Symfony/Component/HttpFoundation/File/UploadedFile.html

我reccomand您使用@assert \圖片約束而不是@Assert \ File約束,這裏解釋:http://symfony.com/doc/current/reference/constraints/Image.html

+0

好的,你的答案幫了我,但現在我得到一個新的錯誤:>文件「http://lorempixel.com/300/300/」不存在 500內部服務器錯誤 - FileNotFoundException – Maxime

+0

像它說的,文件沒有找到,問題是你的鏈接,我試圖用鉻打開鏈接,我得到404未找到,嘗試使用有效的鏈接或下載你想要在你的服務器上的圖像,把它放在網絡文件夾,並使用php魔術常量__DIR__,並且用../ .. – paris93

+0

工作。我通過使用DIR常量的路徑使其工作。現在不幸,我收到一個錯誤:「文件無法上傳。」在我嘗試驗證我的註冊表格之後。儘管我沒有文件上傳字段,但我不應該添加一個,因爲我希望在調用構造函數時使用默認圖像 – Maxime