Adding custom fields to the admin generator
The documentation leaves out one thing in regard to adding your own “virtual field” to the admin generator. In addition to everything in the docs, You have to override the toArray method.
The documentation says:
Custom Fields
As a matter of fact, the fields configured in generator.yml don’t even need to correspond to actual columns defined in the schema. If the related class offers a custom getter, it can be used as a field for the list view; if there is a getter and/or a setter, it can also be used in the edit view. For instance, you can extend the BlogArticle model with a getNbComments() method similar to the one in Listing 14-10.
And you need to do those things, but there’s one missing step. The edit page gets the default for the widgets from the toArray() method, which just iterated over the columns. In order to populate your widget for your “virtual column”, you need to override toArray().
The steps in full are:
- Add the new field to the generator.yml
- Add a getter and a setter to the model
- Add a widget and validator
- Overwrite the toArray() method in the object
Doctrine example (in the model)
public function toArray($deep = true, $prefixKey = false)
{
$arr = parent::toArray($deep, $prefixKey);
$arr['virtual_column'] = $this->getVirtualColumn();
return $arr;
}
public function getVirtualColumn() {
return 'hellow world';
}
public function setVirtualColumn($string) {
//do something
}