Deepanshu Goyal
Deepanshu Goyal

Reputation: 2823

Doctrine 2 Uppercase First Letter

I need to uppercase the first letter of word while fetching data using Select query in Doctrine2.

I tried UCASE , but it is not supported in Doctrine 2.

Is there any other way to Uppercase the first letter in Doctrine2 ?

Upvotes: 3

Views: 2074

Answers (2)

edigu
edigu

Reputation: 10099

You can achieve same effect by utilizing Lifecycle Callbacks if doing this on database level is not really required.

For example, in your entity, write a post-load method like this:

<?php 
namespace MyApp\Entity;

use Doctrine\ORM\Mapping as ORM;

/**
 * @ORM\Entity
 * @ORM\HasLifecycleCallbacks <-- NOTICE THIS ANNOTATION
 */
class MyEntity
{

   /**
    * @ORM\PostLoad <-- AND THIS
    */
    public function capitalizeField()
    {
        $this->field = mb_ucfirst($this->field);
    }

}

Update after two years:

This approach solves the problem. Anyway, in a similar situation I would prefer to change the case before writing the data into the database, if possible. I mean that lifecycle callbacks are not free. Another option is changing the case in presentation/view layer. Today, utilizing the whole event mechanism to change the case of a single value sounds overkill to me.

Upvotes: 2

Paul Maxwell
Paul Maxwell

Reputation: 35603

Do it in MySQL, e.g.

SELECT CONCAT(UPPER(LEFT(the_field, 1)),LOWER(SUBSTRING(the_field, 2))) FROM the_table

or if you don't want to alter the field excpet the first letter:

SELECT CONCAT(UPPER(LEFT(the_field, 1)),SUBSTRING(the_field, 2)) FROM the_table

Upvotes: 0

Related Questions