Home > Symfony 1.3 & 1.4 > Symfony 1.4 Adding custom Filter

Symfony 1.4 Adding custom Filter

I have a deleted_at field in my db that is a time stamp. I wanted to filter my records by records that are deleted and ones that are not.

He’re what i did:

lib/model/xxx.class.php: i added a magic function getDeleted this returns true/false if the record has a deleted_at value:


    public function getDeleted()
    {
        return ($this->deleted_at) ? 1 : 0;
    }

generator.yml: I then add it to my generator to be displayed in the index action. I set it to boolean to have it use a check for on and nothing for off.


config:
  fields:
   deleted:        {type: Boolean}

my xxxFormFilter.class.php: In my filter class i add the deleted widget as a sfWidgetFormChoice with a validator to get the value back from the filter. I also add the magic method: addDeletedColumnQuery which handles my query. Please note i had to hardcode the name of the field that i was running a where on. I should probably just pass this to a doctrine table method that would add the where, but for now this works.


    public function configure()
    {       

        $this->widgetSchema['deleted'] =
                new sfWidgetFormChoice(array(
                        'choices' => array('' => 'yes or no', 1 => 'yes', 0 => 'no')));

        $this->validatorSchema['deleted'] =
                new sfValidatorChoice(array(
                        'required' => false,
                        'choices' => array('', 1, 0)));

    }

    protected function addDeletedColumnQuery(Doctrine_Query $query, $field, $values)
    {
        $rootAlias = $query->getRootAlias();
        $fieldName = "deleted_at";

        if ($values == 0) {
            $query->addWhere(
                    sprintf('%s.%s IS NULL OR %s.%s = ?',
                            $rootAlias, $fieldName, $rootAlias, $fieldName),
                    '');
        }
        else if ($values == 1) {
            $query->addWhere(
                    sprintf('%s.%s IS NOT NULL AND %s.%s <> ?',
                            $rootAlias, $fieldName, $rootAlias, $fieldName),
                    '');
        }
    }
Categories: Symfony 1.3 & 1.4 Tags:
  1. STEEEVE
    March 15th, 2010 at 00:08 | #1

    I’m confused; is this code an example of the wrong way to do this? otherwise why would you call this site “botched code”. doesnt give me much confidence to try this.

  2. lleung
    March 15th, 2010 at 07:51 | #2

    This is the proper way that we know of. This should have been Made clear in the post. Sorry.

  3. July 30th, 2010 at 10:19 | #3

    Hells yeah!

  4. Anil
    December 23rd, 2011 at 06:22 | #4

    That’s good….

  1. No trackbacks yet.