Symfony2 entity field type alternatywy dla "property" lub " toString ()"?

Używając Symfony2 Typ pola entity należy podać opcję property:

$builder->add('customers', 'entity', array(
    'multiple' => true,
    'class'    => 'AcmeHelloBundle:Customer',
    'property' => 'first',
));

Ale czasami to nie wystarczy: pomyśl o dwóch klientach o tej samej nazwie, więc wyświetlanie adresu e-mail (unikalny) byłoby obowiązkowe.

Inną możliwością jest zaimplementowanie __toString() do modelu:

class Customer
{
    public $first, $last, $email;

    public function __toString()
    {
        return sprintf('%s %s (%s)', $this->first, $this->last, $this->email);
    }
}

Wadą tego ostatniego jest to, że jesteś zmuszony do wyświetlania istoty w ten sam sposób we wszystkich swoich formach.

Czy Jest jakiś inny sposób, aby to bardziej elastyczne? chodzi mi o coś w rodzaju funkcji zwrotnej:

$builder->add('customers', 'entity', array(
    'multiple' => true,
    'class'    => 'AcmeHelloBundle:Customer',
    'property' => function($data) {
         return sprintf('%s %s (%s)', $data->first, $data->last, $data->email);
     },
));
Author: j0k, 2012-03-29

3 answers

Uznałem to za bardzo pomocne, i zrobiłem naprawdę łatwy sposób, aby to zrobić za pomocą Twojego kodu, więc oto rozwiązanie

$builder->add('customers', 'entity', array(
'multiple' => true,
'class'    => 'AcmeHelloBundle:Customer',
'property' => 'label',
));

Oraz w klasie Klient (podmiot)

public function getLabel()
{
    return $this->lastname .', '. $this->firstname .' ('. $this->email .')';
}

EH voila: d Właściwość pobiera swój łańcuch z encji, a nie z bazy danych.

 40
Author: Detmud,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2012-04-18 21:46:23

Przekazanie zamknięcia jeszcze nie działa, ale wkrótce zostanie dodane do Symfony: https://github.com/symfony/symfony/issues/4067

 3
Author: Bernhard Schussek,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2012-05-01 19:39:59

Wydaje się, że można to osiągnąć poprzez dodanie następującego bloku po elseif ($this->labelPath) bloku w ObjectChoiceList.php .

elseif (is_callable($this->labelPath)) {
  $labels[$i] = call_user_func($this->labelPath, $choice);
}

Nie próbowałem jednak :).

 1
Author: Mun Mun Das,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2012-03-28 23:26:50