Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
147 views
in Technique[技术] by (71.8m points)

symfony1 - symfony admin filter with join

I have a table, heading, that has an import_profile_id. import_profile has a bank_id.

On my headings list page in my admin, I'd like to add the ability to filter by bank_id. However, since heading doesn't have a bank_id - it needs to go through import_profile to get that - I can't just add a bank_id field and expect it to work.

Can anyone explain how to do this? The closest thing I've found is this post but I don't think it really addresses my issue.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

This can be done by using virtual columns like the post you found. The virtual column is a way to add a new criteria to filter using the autogenerated filter provided by symfony. It works like this:

1 - Go to the generator.yml of the admin module and add the name of the virtual column that will create and add

<!-- apps/backend/modules/module_name/config/generator.yml -->
filter:
     [virtual_column_name, and, other, filter, columns]

2 - In your lib/filter/{TableName}FormFilter.class.php (I think in your case must be HeadingFormFilter) you have to define that virtual column in the configure() method

  public function configure()
  {
      //Type of widget (could be sfWidgetFormChoice with bank names)
      $this->widgetSchema['virtual_column_name'] =  new sfWidgetFormInputText(array(
          'label' => 'Virtual Column Label'
      ));

      //Type of validator for filter
      $this->validatorSchema['virtual_column_name'] = new sfValidatorPass(array ('required' => false));
  }

3 - Override the getFields() of that class to define it in the filter and set the filter function

public function getFields()
{
  $fields = parent::getFields();
  //the right 'virtual_column_name' is the method to filter
  $fields['virtual_column_name'] = 'virtual_column_name';
  return $fields;
}

4 - Finally you have to define the filter method. This method must be named after the add...ColumnQuery pattern, in our case must be addVirtualColumnNameColumnQuery(not a happy name choice :P), so

public function addVirtualColumnNameColumnQuery($query, $field, $value)
{
     //add your filter query!
     //for example in your case
     $rootAlias = $query->getRootAlias();
     $query->innerJoin($rootAlias . '.ImportProfile ip')
           ->andWhere('ip.BankId = ?', $value);

     //remember to return the $query!
     return $query;
}

Done! You can know filter by bank_id.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...