Answer the question
In order to leave comments, you need to log in
How to reuse an entity?
Hello, I'm obsessed with such a task: in general, there is a User entity, in which there are firstName, lastName, username, email and password properties (their number will increase over time); when implementing the registration form, you need to save only two properties - email and password; but when I try to do so, an exception is thrown, where it is written that Doctrina passes absolutely all the parameters that have it, and sets the missing parameters to null. Why does it happen this way? Maybe you need to create your own entity for each implementation of the functionality, or maybe you need a completely different approach? Who knows, or has already encountered this issue, please share, you save me a lot of time.
Answer the question
In order to leave comments, you need to log in
You have two options:
1) either allow fields to be nullable
2) or set a default value for the field.
namespace YourBundle\Entity;
use Doctrine\ORM\Mapping as ORM;
/**
* @ORM\Entity
*/
class User
{
/**
* @ORM\Column(type="integer")
* @ORM\Id
* @ORM\GeneratedValue(strategy="AUTO")
*/
private $id;
/**
* @ORM\Column(type="string", length=100, nullable=true)
*/
private $firstName;
/**
* @ORM\Column(type="string", length=100, nullable=true)
*/
private $lastName;
/**
* @ORM\Column(type="string", length=100)
*/
private $username = "";
/**
* @ORM\Column(type="string", length=100, unique=true)
*/
private $email;
/**
* @ORM\Column(type="string", length=100)
*/
private $password;
// getters & setters
}
Doctrina passes absolutely all the parameters that have it, and sets the missing ones to null. Why does it happen this way?
function __construct() {
$this->firstName = "unknown";
$this->lastName= "unknown";
// и тд
}
alternatively you can use hooks
/**
* @ORM\Entity @ORM\HasLifecycleCallbacks
* @ORM\Table(name="users")
**/
class User
{
/**
* @ORM\PrePersist
*/
public function prePersist()
{
$this->created = new \DateTime('now');
$this->status = self::STATUS_PENDING;
}
/** @ORM\PreUpdate */
public function preUpdate()
{
$this->updated = new \DateTime('now');
}
}
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question