1

I am using Symfony version 2.7.6. I have created an entity named EmployeeBasicInfo having fields

  1. firstname
  2. lastname
  3. identificationCode etc

I have created a callback function for validating Identification code in EmployeeBasicInfo entity itself which looks like

    /**
     * @Assert\Callback(groups={"edit_myinfo"})
     */
    public function validateIdentificationCode(ExecutionContextInterface $context)
    {


        if ($this->getEmployeeFirstName() == 'fakename') {

            $context->buildViolation('This name sounds totally fake!')
                ->atPath('employeeFirstName')
                ->addViolation();


        }
    }

and this callback function works properly

Actually I want such a callback functionality which checks identidfication code against database. I have added $em = $this->getDoctrine()->getManager(); inside the callback function and the error is like Attempted to call an undefined method named "getDoctrine" of class "XXX\EmployeeBundle\Entity\EmployeeBasicInfo".. Please advise me the effective way

2 Answers 2

3

Do not inject the EntityManager in your Entity. One basic concept of the DataMapper-Pattern is, that your entity does not have to know about your data source and its connectors.

I'd suggest to write a custom validation constraint, in which you inject the dependencies you need.

EntityManager, Repository to query, etc. Whatever service suits you.

Have a look at how to create custom constraint validators with dependencies

Sign up to request clarification or add additional context in comments.

4 Comments

in this case I cant add callback function from controller
i have tried adding the same in the repository class. But got the same error
I have reffered this link knpuniversity.com/screencast/question-answer-day/…. In it, they are connecting to the database from the entitty repository class but i still get the error
how can i use this within an entity inside a callback function??
0

I would suggest you use a service to do this

class EmployeeUtility($connection)
{
    public function __construct($conn) { $this->connection = $v; }

    public function validateIdentificationCode($emloyeeId, $validationCode)
    {
        // Your code here
    }
}

In your controller, you inject the service:

$employeeUtility = $this->get('employee.utility');
$employeeUtility->validateIdentificationCode(1,'GF38883dkDdW3373d');

Alternatively, add the code in a repository class.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.