问题
I want to show some fields of an object with SonataAdmin. One of these fields is an integer (status) in the database, but I don't want to show the integer, else a specific string depending on the value of this field.
public function configureListFields(ListMapper $listMapper)
{
$listMapper
->addIdentifier('name')
->add('notice')
->add('start')
->add('end')
->add('status')
;
}
Is it possible?
And a second question: in the same example, I want to add a field which is not mapped in the database (people) because this is calculated with data related with other objects.
public function configureListFields(ListMapper $listMapper)
{
$listMapper
->addIdentifier('name')
->add('notice')
->add('start')
->add('end')
->add('status')
->add('people')
;
}
Can I do this with Sonata Admin?
Thanks in advance.
回答1:
I guess your best way to do this is to make custom setters and getters in your entity.
For example you have the entity user:
private $customState; // NOTE -> NO ORM MAPPING because you don't want an actual column
public function setCustomState() {
if($this->state){
$this->customState = 'yup!';
return $this;
}
$this->customState = 'nope!';
return $this;
}
public function getCustomState() {
return $this->customState;
}
回答2:
Thanks for the answer. However, I've been looking for information on Internet and I've found other way to do this. You can render a specific template for your field. In your Admin class, in the configureListFields function you could do this:
public function configureListFields(ListMapper $listMapper)
{
$listMapper
->addIdentifier('name')
->add('notice')
->add('start')
->add('end')
->add('status', 'string', array('template' => 'YourBundle:YourController:status_field.html.twig'))
->add('Resources', 'string', array('template' => 'YourBundle:YourController:resources_field.html.twig'))
}
For the "status" field, the status_field.html.twig template will be rendered as below:
{% extends 'SonataAdminBundle:CRUD:base_list_field.html.twig' %}
{% block field %}
<div>
{% if object.status == 0 %}
<strong>Inactivo</strong>
{% elseif object.status == 1 %}
<strong>Activo</strong>
{% endif %}
</div>
{% endblock %}
And for my second question, the same solution is valid. The template rendered for the "resources" field would be as below:
{% extends 'SonataAdminBundle:CRUD:base_list_field.html.twig' %}
{% block field %}
<div>
<strong>{{ object.getResources|length }}</strong>
</div>
{% endblock %}
In this way, the object is passed to the template, and you can use its methods to get the information that you need. In this case, the method getResources() is used to display its length.
来源:https://stackoverflow.com/questions/15947799/problems-showing-fields-with-sonata-admin-symfony-2-0