I have 2 entities: person and emailaddress
class Person
{
/**
* #var int
*
* #ORM\Column(name="id", type="integer")
* #ORM\Id
* #ORM\GeneratedValue(strategy="AUTO")
*/
private $id;
/**
* #var string
*
* #ORM\Column(name="name", type="string", length=255)
*/
private $name;
/**
* #var Emailaddress[]
* #ORM\OneToMany(targetEntity="Emailaddress", mappedBy="person", cascade={"ALL"})
*
*/
private $emails;
public function __construct() {
$this->emails = new ArrayCollection();
}
/**
* Get id
*
* #return int
*/
public function getId()
{
return $this->id;
}
/**
* Set name
*
* #param string $name
*
* #return Person
*/
public function setName($name)
{
$this->name = $name;
return $this;
}
/**
* Get name
*
* #return string
*/
public function getName()
{
return $this->name;
}
/**
* Add email
*
* #param \AppBundle\Entity\Emailaddress $email
*
* #return Person
*/
public function addEmail(\AppBundle\Entity\Emailaddress $email)
{
$this->emails[] = $email;
$email->setPerson($this);
return $this;
}
/**
* Remove email
*
* #param \AppBundle\Entity\Emailaddress $email
*/
public function removeEmail(\AppBundle\Entity\Emailaddress $email)
{
$this->emails->removeElement($email);
}
/**
* Get emails
*
* #return \Doctrine\Common\Collections\Collection
*/
public function getEmails()
{
return $this->emails;
}
}
class Emailaddress
{
/**
* #var int
*
* #ORM\Column(name="id", type="integer")
* #ORM\Id
* #ORM\GeneratedValue(strategy="AUTO")
*/
private $id;
/**
* #var string
*
* #ORM\Column(name="emailaddress", type="string", length=100)
*/
private $emailaddress;
/**
* #var Person
* #ORM\ManyToOne(targetEntity="Person", inversedBy="emails")
* #ORM\JoinColumn(name="person_id", referencedColumnName="id")
*/
private $person;
/**
* Get id
*
* #return int
*/
public function getId()
{
return $this->id;
}
/**
* Set emailaddress
*
* #param string $emailaddress
*
* #return Emailaddress
*/
public function setEmailaddress($emailaddress)
{
$this->emailaddress = $emailaddress;
return $this;
}
/**
* Get emailaddress
*
* #return string
*/
public function getEmailaddress()
{
return $this->emailaddress;
}
/**
* Set person
*
* #param \AppBundle\Entity\Person $person
*
* #return Emailaddress
*/
public function setPerson(\AppBundle\Entity\Person $person = null)
{
$this->person = $person;
return $this;
}
/**
* Get person
*
* #return \AppBundle\Entity\Person
*/
public function getPerson()
{
return $this->person;
}
}
In EmailaddressType I have:
$builder->add('email');
And in PersonType:
$builder->add('name')
->add('emails', CollectionType::class, array(
'entry_type' => EmailAddressType::class,
'allow_add' => true,
));
Now when the form is generated on the emails field does not display anything.
How can I generate email fields?
Thanks
I configured my BjyAuthorised using SamUser and other resources online. I thought the following configuration suppose to block all users but 'admin'. However, role of a user does not affect the result. Any user can access this resource. Please help.
My BjyAuthorise config file:
<?php
return array(
'bjyauthorize' => array(
'default_role' => 'guest',
'resource_providers' => array(
'BjyAuthorize\Provider\Resource\Config' => array(
'OnlineFieldEvaluation\Controller\OnlineFieldEvaluation' => array(),
),
),
'rule_providers' => array(
'BjyAuthorize\Provider\Rule\Config' => array(
'allow' => array(
array(array('admin'), 'OnlineFieldEvaluation\Controller\OnlineFieldEvaluation', array('index')),
),
),
),
'identity_provider' => 'BjyAuthorize\Provider\Identity\AuthenticationIdentityProvider',
'BjyAuthorize\Provider\Role\ObjectRepositoryProvider' => array(
'object_manager' => 'doctrine.entity_manager.orm_default',
'role_entity_class' => 'Application\Entity\Role',
),
),
// 'guards' => array(
// 'BjyAuthorize\Guard\Controller' => array(
// array('controller' => 'OnlineFieldEvaluation\Controller\OnlineFieldEvaluation',
// 'action' => array('index'),
// 'roles' => array('admin')),
// ),
// ),
);
Module config file
<?php
namespace OnlineFieldEvaluation;
return array(
'controllers' => array(
'invokables' => array(
'OnlineFieldEvaluation\Controller\OnlineFieldEvaluation' => 'OnlineFieldEvaluation\Controller\OnlineFieldEvaluationController',
),
),
// The following section is new and should be added to your file
'router' => array(
'routes' => array(
'OnlineFieldEvaluation' => array(
'type' => 'segment',
'options' => array(
'route' => '/onlinefieldevaluation[/][:action][/:id]',
'constraints' => array(
'action' => '[a-zA-Z][a-zA-Z0-9_-]*',
'id' => '[0-9]+',
),
'defaults' => array(
'controller' => 'OnlineFieldEvaluation\Controller\OnlineFieldEvaluation',
'action' => 'index',
),
),
),
),
),
'view_manager' => array(
'template_path_stack' => array(
'OnlineFieldEvaluation' => __DIR__ . '/../view',
),
),
// Doctrine config
'doctrine' => array(
'driver' => array(
__NAMESPACE__ . '_driver' => array(
'class' => 'Doctrine\ORM\Mapping\Driver\AnnotationDriver',
'cache' => 'array',
'paths' => array(__DIR__ . '/../src/' . __NAMESPACE__ . '/Entity')
),
'orm_default' => array(
'drivers' => array(
__NAMESPACE__ . '\Entity' => __NAMESPACE__ . '_driver'
)
),
),
),
);
Systemuser class
<?php
namespace Application\Entity;
use BjyAuthorize\Provider\Role\ProviderInterface;
use Doctrine\Common\Collections\ArrayCollection;
use Doctrine\ORM\Mapping as ORM;
use ZfcUser\Entity\UserInterface;
/**
* Systemuser
*
* #ORM\Table(name="systemuser",uniqueConstraints={#ORM\UniqueConstraint(name="email_idx", columns={"email"})})
* #ORM\Entity
* ORM\Entity(repositoryClass="Application\Entity\Repository\SystemuserRepository")
*/
class Systemuser implements UserInterface, ProviderInterface {
/**
* #var int
* #ORM\Id
* #ORM\Column(type="integer")
* #ORM\GeneratedValue(strategy="AUTO")
*/
private $id;
/**
* #var string
*
* #ORM\Column(name="email", type="string", length=100, nullable=false)
*/
private $email;
/**
* #var string
* #ORM\Column(name="displayname", type="string", length=50, nullable=true)
*/
protected $displayName;
/**
* #var string
*
* #ORM\Column(name="username", type="string", length=100, nullable=true)
*/
private $username;
/**
* #var string
*
* #ORM\Column(name="password", type="string", length=64, nullable=false)
*/
private $password;
/**
* #var string $country
*
* #ORM\Column(type="string", length=255, nullable=true)
*/
private $country;
/**
* var \Application\Entity\Role
*
* ORM\ManyToOne(targetEntity="Application\Entity\Role")
* ORM\JoinColumns({
* ORM\JoinColumn(name="role_id", referencedColumnName="id",nullable=true)
* })
*/
//private $role;
/**
* #var \Doctrine\Common\Collections\Collection
* #ORM\ManyToMany(targetEntity="Application\Entity\Role")
* #ORM\JoinTable(name="users_roles",
* joinColumns={#ORM\JoinColumn(name="user_id", referencedColumnName="id")},
* inverseJoinColumns={#ORM\JoinColumn(name="role_id", referencedColumnName="id")}
* )
*/
protected $roles;
/**
* Initialies the roles variable.
*/
public function __construct()
{
$this->roles = new ArrayCollection();
}
/**
* Get role.
*
* #return array
*/
public function getRoles()
{
return $this->roles->getValues();
}
/**
* Add a role to the user.
*
* #param Role $role
*
* #return void
*/
public function addRole($role)
{
$this->roles[] = $role;
}
/**
* Get id
*
* #return integer
*/
public function getId()
{
return $this->id;
}
/**
* Set id.
*
* #param int $id
* #return UserInterface
*/
public function setId($id) {
$this->id = $id;
}
/**
* Set email
*
* #param string $email
* #return Systemuser
*/
public function setEmail($email)
{
$this->email = $email;
return $this;
}
/**
* Get email
*
* #return string
*/
public function getEmail()
{
return $this->email;
}
/**
* Set username
*
* #param string $username
* #return Systemuser
*/
public function setUsername($username)
{
$this->username = $username;
return $this;
}
/**
* Get username
*
* #return string
*/
public function getUsername()
{
return $this->username;
}
/**
* Set password
*
* #param string $password
* #return Systemuser
*/
public function setPassword($password)
{
$this->password = $password;
return $this;
}
/**
* Get password
*
* #return string
*/
public function getPassword()
{
return $this->password;
}
/**
* Set displayname
*
* #param string $displayName
* #return Systemuser
*/
public function setDisplayname($displayname)
{
$this->displayName= $displayname;
return $this;
}
/**
* Get displayname
*
* #return string
*/
public function getDisplayname()
{
return $this->displayName;
}
/**
* Set country
*
* #param string $country
* #return Conference
*/
public function setCountry($country)
{
$this->country = $country;
return $this;
}
/**
* Get country
*
* #return string
*/
public function getCountry()
{
return $this->country;
}
/**
* Get state.
*
* #return int
*/
public function getState() {
return null;
}
/**
* Set state.
*
* #param int $state
* #return UserInterface
*/
public function setState($state) {
//does nothing
}
/**
* Set role
*
* #param \Application\Entity\Role $role
* #return Systemuser
// */
// public function setRole(\Application\Entity\Role $role = null)
// {
// $this->role = $role;
//
// return $this;
// }
/**
* Get role
*
* #return \Application\Entity\Role
*/
// public function getRole()
// {
// return $this->role;
// }
}
Role class
<?php
namespace Application\Entity;
use BjyAuthorize\Acl\HierarchicalRoleInterface;
use Doctrine\ORM\Mapping as ORM;
//use Zend\Permissions\Acl\Role\RoleInterface;
/**
* Role
*
* #ORM\Table(name="role")
* #ORM\Entity
* ORM\Entity(repositoryClass="Application\Entity\Repository\RoleRepository")
*/
class Role implements HierarchicalRoleInterface
{
/**
* #var string
*
* #ORM\Column(name="id", type="string", length=20, nullable=false)
* #ORM\Id
*/
private $id;
/**
* #var string
*
* #ORM\Column(name="name", type="string", length=100, nullable=false)
*/
private $name;
/**
* #var Role
* #ORM\ManyToOne(targetEntity="Application\Entity\Role")
*/
protected $parent;
public function getRoleId() {
return $this->getId();
}
/**
* Get id
*
* #return integer
*/
public function getId()
{
return $this->id;
}
/**
*
* #param string $id
*/
public function setId( $id ){
$this->id = $id;
}
/**
* Set name
*
* #param string $name
* #return Role
*/
public function setName($name)
{
$this->name = $name;
return $this;
}
/**
* Get name
*
* #return string
*/
public function getName()
{
return $this->name;
}
/**
* Get the parent role
*
* #return Role
*/
public function getParent()
{
return $this->parent;
}
/**
* Set the parent role.
*
* #param Role $parent
*
* #return void
*/
public function setParent(Role $parent)
{
$this->parent = $parent;
}
}
I finally succeeded to configure the BjyAuthorize with the following setup. However, I am still unclear on how can use 'resource_providers' and 'rule_providers' . Looks like guards are functioning well weather I define resources and rules, or I do not. I am not sure what difference those two config properties suppose to make.
bjyauthorize config file
<?php
return array(
'bjyauthorize' => array(
'identity_provider' => 'BjyAuthorize\Provider\Identity\AuthenticationIdentityProvider',
'role_providers' => array(
'BjyAuthorize\Provider\Role\ObjectRepositoryProvider' => array(
'object_manager' => 'doctrine.entitymanager.orm_default',
'role_entity_class' => 'Application\Entity\Role',
),
),
'default_role' => 'guest',
'resource_providers' => array(
'BjyAuthorize\Provider\Resource\Config' => array(
'OnlineFieldEvaluation\Controller\OnlineFieldEvaluation' => array(),
),
),
'rule_providers' => array(
'BjyAuthorize\Provider\Rule\Config' => array(
'allow' => array(
// ...
),
'deny' => array(
// ...
),
),
),
'guards' => array(
'BjyAuthorize\Guard\Controller' => array(
array(
'controller' => 'zfcuser',
'roles' => array('guest')
),
array('controller' => 'OnlineFieldEvaluation\Controller\OnlineFieldEvaluation',
'action' => array('index'),
'roles' => array('student')),
),
),
),
);
Systemuser.php
<?php
/**
* BjyAuthorize Module (https://github.com/bjyoungblood/BjyAuthorize)
*
* #link https://github.com/bjyoungblood/BjyAuthorize for the canonical source repository
* #license http://framework.zend.com/license/new-bsd New BSD License
*/
namespace Application\Entity;
use BjyAuthorize\Provider\Role\ProviderInterface;
use Doctrine\Common\Collections\ArrayCollection;
use Doctrine\ORM\Mapping as ORM;
use ZfcUser\Entity\UserInterface;
/**
* An example of how to implement a role aware user entity.
*
* #ORM\Entity
* #ORM\Table(name="systemuser")
*
* #author Tom Oram <tom#scl.co.uk>
*/
class Systemuser implements UserInterface, ProviderInterface
{
/**
* #var int
* #ORM\Id
* #ORM\Column(type="integer")
* #ORM\GeneratedValue(strategy="AUTO")
*/
protected $id;
/**
* #var string
* #ORM\Column(type="string", length=255, unique=true, nullable=true)
*/
protected $username;
/**
* #var string
* #ORM\Column(type="string", unique=true, length=255)
*/
protected $email;
/**
* #var string
* #ORM\Column(type="string", length=50, nullable=true)
*/
protected $displayName;
/**
* #var string
* #ORM\Column(type="string", length=128)
*/
protected $password;
/**
* #var int
*/
protected $state;
/**
* #var \Doctrine\Common\Collections\Collection
* #ORM\ManyToMany(targetEntity="Application\Entity\Role")
* #ORM\JoinTable(name="users_roles",
* joinColumns={#ORM\JoinColumn(name="user_id", referencedColumnName="id")},
* inverseJoinColumns={#ORM\JoinColumn(name="role_id", referencedColumnName="id")}
* )
*/
protected $roles;
/**
* Initialies the roles variable.
*/
public function __construct()
{
$this->roles = new ArrayCollection();
}
/**
* Get id.
*
* #return int
*/
public function getId()
{
return $this->id;
}
/**
* Set id.
*
* #param int $id
*
* #return void
*/
public function setId($id)
{
$this->id = (int) $id;
}
/**
* Get username.
*
* #return string
*/
public function getUsername()
{
return $this->username;
}
/**
* Set username.
*
* #param string $username
*
* #return void
*/
public function setUsername($username)
{
$this->username = $username;
}
/**
* Get email.
*
* #return string
*/
public function getEmail()
{
return $this->email;
}
/**
* Set email.
*
* #param string $email
*
* #return void
*/
public function setEmail($email)
{
$this->email = $email;
}
/**
* Get displayName.
*
* #return string
*/
public function getDisplayName()
{
return $this->displayName;
}
/**
* Set displayName.
*
* #param string $displayName
*
* #return void
*/
public function setDisplayName($displayName)
{
$this->displayName = $displayName;
}
/**
* Get password.
*
* #return string
*/
public function getPassword()
{
return $this->password;
}
/**
* Set password.
*
* #param string $password
*
* #return void
*/
public function setPassword($password)
{
$this->password = $password;
}
/**
* Get state.
*
* #return int
*/
public function getState()
{
return $this->state;
}
/**
* Set state.
*
* #param int $state
*
* #return void
*/
public function setState($state)
{
$this->state = $state;
}
/**
* Get role.
*
* #return array
*/
public function getRoles()
{
return $this->roles->getValues();
}
/**
* Add a role to the user.
*
* #param Role $role
*
* #return void
*/
public function addRole($role)
{
$this->roles[] = $role;
}
}
Role.php
<?php
/**
* BjyAuthorize Module (https://github.com/bjyoungblood/BjyAuthorize)
*
* #link https://github.com/bjyoungblood/BjyAuthorize for the canonical source repository
* #license http://framework.zend.com/license/new-bsd New BSD License
*/
namespace Application\Entity;
use BjyAuthorize\Acl\HierarchicalRoleInterface;
use Doctrine\ORM\Mapping as ORM;
/**
* An example entity that represents a role.
*
* #ORM\Entity
* #ORM\Table(name="role")
*
* #author Tom Oram <tom#scl.co.uk>
*/
class Role implements HierarchicalRoleInterface
{
/**
* #var int
* #ORM\Id
* #ORM\Column(type="integer")
* #ORM\GeneratedValue(strategy="AUTO")
*/
protected $id;
/**
* #var string
* #ORM\Column(type="string", length=255, unique=true, nullable=true)
*/
protected $roleId;
/**
* #var Role
* #ORM\ManyToOne(targetEntity="Application\Entity\Role")
*/
protected $parent;
/**
* Get the id.
*
* #return int
*/
public function getId()
{
return $this->id;
}
/**
* Set the id.
*
* #param int $id
*
* #return void
*/
public function setId($id)
{
$this->id = (int)$id;
}
/**
* Get the role id.
*
* #return string
*/
public function getRoleId()
{
return $this->roleId;
}
/**
* Set the role id.
*
* #param string $roleId
*
* #return void
*/
public function setRoleId($roleId)
{
$this->roleId = (string) $roleId;
}
/**
* Get the parent role
*
* #return Role
*/
public function getParent()
{
return $this->parent;
}
/**
* Set the parent role.
*
* #param Role $parent
*
* #return void
*/
public function setParent(Role $parent)
{
$this->parent = $parent;
}
}
In the doc it's said:"By default, the Zend Framework MVC registers an initializer that will inject the ServiceManager instance, which is an implementation of Zend\ServiceManager\ServiceLocatorInterface, into any class implementing Zend\ServiceManager\ServiceLocatorAwareInterface."
so I tried this:
interface ModelResourceInterface extends ServiceLocatorAwareInterface
{
}
interface ServiceModelResourceInterface extends ModelResourceInterface
{
public function fetch($uri, $method, $parameters, $options, $encodeType);
}
namespace Ssports\Model\Resource\Service\Http;
use Ssports\Model\Resource\Service\ServiceModelResourceInterface;
use Zend\ServiceManager\ServiceLocatorInterface;
use Zend\Http\Client;
use Zend\Http\Request;
use Ssports\Model\Resource\Service\ConnectionException;
abstract class AbstractHttpServiceModelResource implements ServiceModelResourceInterface
{
/**
*
* #var Zend\ServiceManager\ServiceLocatorInterface;
*/
protected $serviceLocator;
/**
* Constructor
*/
function __construct()
{
$this->init();
}
/**
* Extend Constructor
*/
public function init()
{}
/**
* (non-PHPdoc)
*
* #see \Zend\ServiceManager\ServiceLocatorAwareInterface::setServiceLocator()
*
*/
public function setServiceLocator(ServiceLocatorInterface $serviceLocator)
{
$this->serviceLocator = $serviceLocator;
}
/**
* (non-PHPdoc)
*
* #see \Ssports\Model\Resource\Service\ServiceModelResourceInterface::fetch()
*
*/
public function fetch($uri, $method, $parameters = null, $options = null, $encodeType = null)
{
try {
//something raise \RuntimeException
} catch (\RuntimeException $e) {
$this->getServiceLocator()->get('Log\Web');
throw new ConnectionException();
}
}
/**
* (non-PHPdoc)
*
* #see \Zend\ServiceManager\ServiceLocatorAwareInterface::getServiceLocator()
*
*/
public function getServiceLocator()
{
return $this->serviceLocator;
}
}
I extend this abstract class with some model resource class, and run it, and an exception throw to say that I'm calling get on a non-object.
Seem that the service manager is not being injected to my abstract class, and the return of getServiceLocator is NULL.
Any thing I missed to make it right?
Have you tried to use the service locator trait?
It can be found in \Zend\ServiceManager\ServiceLocatorAwareTrait
However this requires PHP 5.4 to work...
To use a trait do the following
class Class1
{
use Zend\ServiceManager\ServiceLocatorAwareTrait;
}
You can access the service locator then, or at least that is how i had to do it when i needed to load the service locator.
My join looks like this in sql:
SELECT m.*
FROM settings AS s
LEFT JOIN modules AS m on s.name = m.module
WHERE s.value = 1
AND s.category = 'module_status'
I cannot figure out how to reproduce this in Doctrine 2. Any help is greatly appreciated!
Here are my entities:
namespace Entities;
use Doctrine\Common\Collections\ArrayCollection;
/**
* Modules
*
* #Table(name="modules")
* #Entity(repositoryClass="Repositories\Modules")
*/
class Modules
{
/**
* #var integer $id
*
* #Column(name="id", type="integer", nullable=false)
* #Id
* #GeneratedValue(strategy="IDENTITY")
*/
private $id;
/**
* #var string $module
* #Column(name="module", type="string", length=255, nullable=false)
*/
private $module;
/**
* #var string $label
* #Column(name="label", type="string", length=255, nullable=false)
*/
private $label;
/**
* #var string $package
*
* #Column(name="package", type="string", length=255, nullable=true)
*/
private $package;
/**
* #var string $path
*
* #Column(name="path", type="string", length=255, nullable=true)
*/
private $path;
/**
* #var float $version
*
* #Column(name="version", type="float", nullable=false)
*/
private $version;
public function getId() {
return $this->id;
}
public function getModule() {
return $this->module;
}
public function getLabel() {
return $this->label;
}
public function getPackage() {
return $this->package;
}
public function getPath() {
return $this->path;
}
public function getVersion() {
return $this->version;
}
public function setId($id) {
$this->id = $id;
}
public function setModule($module) {
$this->module = $module;
}
public function setLabel($label) {
$this->label = $label;
}
public function setPackage($package) {
$this->package = $package;
}
public function setPath($path) {
$this->path = $path;
}
public function setVersion($version) {
$this->version = $version;
}
}
namespace Entities;
use Doctrine\ORM\Mapping as ORM;
/**
* Settings
*
* #Table(name="settings")
* #Entity(repositoryClass="Repositories\Settings")
*/
class Settings
{
/**
* #var integer $id
*
* #Column(name="id", type="integer", nullable=false)
* #Id
* #GeneratedValue(strategy="IDENTITY")
*/
private $id;
/**
* #var string $name
*
* #Column(name="name", type="string", length=255, nullable=true)
*/
private $name;
/**
* #var string $category
*
* #Column(name="category", type="string", length=255, nullable=true)
*/
private $category;
/**
* #var text $value
*
* #Column(name="value", type="text", nullable=true)
*/
private $value;
public function getId() {
return $this->id;
}
public function getName() {
return $this->name;
}
public function setName($name) {
$this->name = $name;
}
public function getCategory() {
return $this->category;
}
public function setCategory($category) {
$this->category = $category;
}
public function getValue() {
return $this->value;
}
public function setValue($value) {
$this->value = $value;
}
}
First, you need an association configured between the Settings and Modules entities. I'm assuming the relationship between the two is many-to-many:
Class Modules
{
/**
* #ManyToMany(targetEntity="Settings", inversedBy="modules")
* #JoinTable(name="modules_settings")
*/
private $settings;
}
Class Settings
{
/**
* #ManyToMany(targetEntity="Modules", mappedBy="settings")
*/
private $modules;
}
Then your query syntax would look like this:
$qb->select('s', 'm')
->from('Entities\Settings', 's')
->leftJoin('s.modules')
->where('s.value = 1');
I can't tell what's going on in your AND clause, but if what you have is correct, then you simply add this line to the end of your query:
->andWhere('s.category = m.status');
Thanks for the help. This is what the query ended up being:
$qb = $this->_em->createQueryBuilder()
->select('m')
->from('Entities\Modules', 'm')
->leftJoin('m.settings', 's')
->where('s.value = :enabled')
->andWhere('s.category = :moduleStatus')
->setParameter('moduleStatus', 'module_status')
->setParameter('enabled', 1)
->getQuery();
This is how I configured the modules entity:
/**
* #OneToOne(targetEntity="Entities\Settings")
* #JoinColumn(name="module", referencedColumnName="name")
*/
private $settings;
I am trying to upload image files with Doctrine in Symfony2 but I am getting the following error.: SQLSTATE[23000]: Integrity constraint violation: 1048 Column 'name' cannot be null.
Here is my Entity class
<?php
// src/Acme/DemoBundle/Entity/Document.php
namespace Acme\DemoBundle\Entity;
use Doctrine\ORM\Mapping as ORM;
use Symfony\Component\Validator\Constraints as Assert;
/**
* #ORM\Entity
* #ORM\HasLifecycleCallbacks
* #ORM\Table(name="document")
*/
class Document
{
/**
* #ORM\Id
* #ORM\Column(type="integer")
* #ORM\GeneratedValue(strategy="AUTO")
*/
public $id;
/**
* #ORM\Column(type="string", length=255)
* #Assert\NotBlank
*/
public $name;
/**
* #ORM\Column(type="string", length=255, nullable=true)
*/
public $path;
/**
* #Assert\File(maxSize="6000000")
*/
public $file;
public function getUploadRootDir()
{
return '/uploads';
}
/**
* Get id
*
* #return integer $id
*/
public function getId()
{
return $this->id;
}
/**
* Set name
*
* #param string $name
*/
public function setName($name = 'akshaya')
{
$this->name = $name;
}
/**
* Get name
*
* #return string $name
*/
public function getName()
{
return $this->name;
}
/**
* Set path
*
* #param string $path
*/
public function setPath($path)
{
$this->path = $path;
}
/**
* Get path
*
* #return string $path
*/
public function getPath()
{
return $this->path;
}
/**
* #ORM\PrePersist()
*/
public function preUpload()
{
if ($this->file) {
$this->setPath($this->file->guessExtension());
}
}
/**
* #ORM\PostPersist()
*/
public function upload()
{
if (!$this->file) {
return;
}
try{
$this->file->move($this->getUploadRootDir(), $this->id.'.'.$this->file->guessExtension());
}
catch(FilePermissionException $e)
{
return false;
}
catch(\Exception $e)
{
throw new \Exception($e->getMessage());
}
unset($this->file);
}
/**
* #ORM\PreRemove()
*/
public function removeUpload()
{
if ($file = $this->getFullPath()) {
unlink($file);
}
}
public function getFullPath()
{
return null === $this->path ? null : $this->getUploadRootDir().'/'.$this->id.'.'.$this->path;
}
}
Here is the related Controller class
<?php
namespace Acme\DemoBundle\Controller;
use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use Symfony\Component\HttpFoundation\RedirectResponse;
use Acme\DemoBundle\Form\ContactForm;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Route;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Template;
use Imagine\Gd\Imagine;
use Imagine\Image\Box;
use Acme\DemoBundle\Entity\Document;
class FileUploadController extends Controller
{
protected $file;
protected $document;
public function indexAction()
{
$this->document = new Document();
$form = $this->get('form.factory')
->createBuilder('form')
->add('name','text')
->add('file','file')
->getForm();
$request = $this->get('request');
if ($request->getMethod() === 'POST') {
$form->bindRequest($request);
if ($form->isValid()) {
$em = $this->get('doctrine.orm.entity_manager');
$this->document->upload();
$em->persist($this->document);
$em->flush();
$this->get('session')->setFlash('notice', 'The file is uploaded!');
}
}
return $this->render('AcmeDemoBundle:FileUpload:index.html.twig',
array("form"=>$form->createView()));
}
}
This error is not related to the upload,
The upload seems to work, but it's the insert in the database who has a problem.
The value you have provided for name is null or empty. Your database schema don't allow null value for name column.
I see 3 possible solutions:
add this annotation to the $name property: #ORM\Column(type="string", length=255, nullable="true")
provide a value for the name field, enter a value when you submit your form.
set a default name when constructing your object:
public function __construct() {
$this->name = 'foo';
}