AliHichem / AliDatatableBundle

Symfony2 Ajax Datagrid Bundle for doctrine2 entities
MIT License
112 stars 72 forks source link

Filtering doesn't work with aliases #77

Closed alexmocanu closed 10 years ago

alexmocanu commented 10 years ago

I have a datatable that pulls data from several tables and since some fields have the same name I had to use aliases.

The datatable itself and the sorting part works but filtering doesn't. It uses the "fieldname AS alias" part in the WHERE condition:

WHERE client.status=:status AND country.name as countryName like '%Bulgaria%' 

My datatable definition looks like this:

    $datatable->setEntity('<NAMESPACE>ClientBundle:Client', 'client')->setFields(
        array(
            $translator->trans("user_interface.name")      => "client.name",
            $translator->trans("user_interface.username")  => "client.username",
            $translator->trans("user_interface.country")   => "country.name as countryName",
            $translator->trans("user_interface.suffix")    => "client.suffix",
            $translator->trans("user_interface.user_name") => "user.username as userUsername",
            $translator->trans("user_interface.storage")   => "storage.name as StorageName",
            //$translator->trans("user_interface.password") => "client.password",
            "_identifier_"                                 => 'client.id',
        )
    )
    ->setRenderers( [...some renderers...] )
    ->addJoin('client.user', 'user', \Doctrine\ORM\Query\Expr\Join::LEFT_JOIN)
    ->addJoin('client.storage', 'storage', \Doctrine\ORM\Query\Expr\Join::INNER_JOIN)
    ->addJoin('client.country', 'country', \Doctrine\ORM\Query\Expr\Join::INNER_JOIN)
    ->setWhere("client.status=:status", array('status' => 1))    
    ->setOrder(self::ORDER_FIELD, self::ORDER_DIRECTION)
    ->setDatatableId('id')
    ->setHasAction(true)
    ->setSearch(true)
    ->setSearchFields(array(0, 1, 2, 3, 4));

Removing the countryName alias will kill the datatable entirely:

Undefined offset: 6 in [path]vendor/ali/datatable/Ali/DatatableBundle/Util/Datatable.php on line 134

A solution is to update the _addSearch function like this:

    protected function _addSearch(\Doctrine\ORM\QueryBuilder $queryBuilder)
    {
        if ($this->search == TRUE)
        {
            $request       = $this->request;
            $search_fields = array_values($this->fields);
            foreach ($search_fields as $i => $search_field)
            {
                if ($request->get("sSearch_{$i}"))
                {
/* additions - if $search_field contains space use the first part */
                    $field = explode(' ',trim($search_field));
                    $search_field = $field[0];
/* end additions */
                    $queryBuilder->andWhere(" $search_field like '%{$request->get("sSearch_{$i}")}%' ");
                }
            }
        }
    }
AliHichem commented 10 years ago

the Fix of issue #81 resolves this bug too .