bshaffer / sfHadoriThemePlugin

symfony admin generator with a beautiful theme and clean generated code.
MIT License
21 stars 6 forks source link

Foreign key fields are not sortable in list context #21

Closed tdmedia closed 12 years ago

tdmedia commented 12 years ago

Despite using the is_real parameter in the generator, foreign key fields are not sortable in the list context.

bshaffer commented 12 years ago

I was able to get a field to link using the is_real parameter. Take the example below for a model caleld BlogPost, In generator.yml:

  list:
    display:  
     - =title
     author_first_name: { is_real: true }
     author_last_name: { is_real: true }

And in actions.class.php:

public function getBaseQuery()
{
    $query = parent::getBaseQuery();
    $a = $query->getRootAlias();
    $query
        ->leftJoin($a.'.Author au')
        ->addSelect($a.'.*, au.*, au.last_name as author_last_name, au.first_name as author_first_name');

    return $query;
}

As long as the field is returned as part of the query, the field can be sorted as expected.

The exception here is if the field already exists or the field is a relation. For example, I could not sort by a column called Author, since author is a relation on BlogPost.

As naming a column by a relation is the only way to gain the "auto-linking" functionality, I have added another way to gain auto-linking functionality (38f26ba8d93423e38f1760084082), which allows you to provide a relation parameter for a column in order to link it to another model. So using the example above:

  list:
    display:  
     - =title
     author_first_name: { is_real: true }
     author_last_name: { is_real: true, relation: Author }

Would link the "Author Last Name" column to the sfGuardUser Hadori model (or whatever class Author happens to be!). So, a full example may look like this:

generator.yml:

  list:
    display:  
     - =title
     author_name: { is_real: true, relation: Author }

actions.class.php

public function getBaseQuery()
{
    $query = parent::getBaseQuery();
    $a = $query->getRootAlias();
    $query
        ->leftJoin($a.'.Author au')
        ->addSelect($a.'.*, au.*, CONCAT(au.first_name, " ", au.last_name) as author_name');

    return $query;
}