2012-06-12 58 views

回答

1

嗯,有些同事(@ benji07)在工作中已經寫的:

/** 
* Set filters 
* @param string $name Name of the key to store filters 
* @param array $filters Filters 
*/ 
public function setFilters($name, array $filters = array()) 
{ 
    foreach ($filters as $key => $value) { 
     // Transform entities objects into a pair of class/id 
     if (is_object($value)) { 
      if ($value instanceof ArrayCollection) { 
       if (count($value)) { 
        $filters[$key] = array(
         'class' => get_class($value->first()), 
         'ids' => array() 
        ); 
        foreach ($value as $v) { 
         $identifier = $this->getDoctrine()->getEntityManager()->getUnitOfWork()->getEntityIdentifier($v); 
         $filters[$key]['ids'][] = $identifier['id']; 
        } 
       } 
      } 
      elseif (!$value instanceof \DateTime) { 
       $filters[$key] = array(
        'class' => get_class($value), 
        'id' => $this->getDoctrine()->getEntityManager()->getUnitOfWork()->getEntityIdentifier($value) 
       ); 
      } 
     } 
    } 

    $this->getRequest()->getSession()->set(
     $name, 
     $filters 
    ); 
} 

/** 
* Get Filters 
* @param string $name Name of the key to get filters 
* @param array $filters Filters 
* 
* @return array 
*/ 
public function getFilters($name, array $filters = array()) 
{ 
    $filters = array_merge(
     $this->getRequest()->getSession()->get(
      $name, 
      array() 
     ), 
     $filters 
    ); 

    foreach ($filters as $key => $value) { 
     // Get entities from pair of class/id 
     if (is_array($value) && isset($value['class']) && isset($value['id'])) { 
      $filters[$key] = $this->getDoctrine()->getEntityManager()->find($value['class'], $value['id']); 
     } elseif (isset($value['ids'])) { 
      $data = $this->getDoctrine()->getEntityManager()->getRepository($value['class'])->findBy(array('id' => $value['ids'])); 
      $filters[$key] = new ArrayCollection($data); 
     } 
    } 

    return $filters; 
} 

它適用於基本的實體,以及多值選擇

PS:不要忘了添加使用ArrayCollection

免責聲明,我們不知道這是否是一種好的做法,我們知道至少有一個限制:您必須確保您嘗試保存在會話中的對象具有id(這是99.9%的情況)

相關問題