如何生成自定义代码symfony 2

I am using symfony 2 with doctrine. I want to create custom id for the product table.

Eg:

Product code P1000-1 P1000-2 P1000-3

How to generate this ?

How about you write a small piece of custom function to retrieve the last inserted ID and then add 'P1000-' before the id. See below,

public function getLastInsertedId($entity)
{
    $em = $this->getDoctrine()->getManager();
    $result = $em->createQueryBuilder();
    $last_inserted_id = $result->select('MAX(p.id) as id')
            ->from($entity, 'p')
            ->getQuery()
            ->getSingleResult(\Doctrine\ORM\Query::HYDRATE_ARRAY);        
    return 'P1000-'.$last_inserted_id['id'];
}

Hope this helps. Cheers!

if it's sequential, you can try @GeneratedValue

If you need more flexibility , you have to use a custom Id Generator. Create a class which extends AbstractIdGenerator and implement the generate() method, as per your requirement.

and in your entity, use the following Annotations .

 @ORM\GeneratedValue(strategy="CUSTOM")
 @ORM\CustomIdGenerator(class="\Some\Bundle\Util\CustomGenerator")

on the Id Field , make sure the generate() method returns the same type as that used in the field .