Search code examples
symfony1symfony-1.4

How to store the choice array_keys as values when using sfWidgetFormChoice when multiple equals true


Here’s my widget in the Form.Class:

$this->widgetSchema['schools'] = new sfWidgetFormChoice(array(
    'choices'        => Doctrine_Core::getTable('school')->getUsersSchools($userId),
    'renderer_class' => 'sfWidgetFormSelectDoubleList', 
    'renderer_options' => array(
        'label_unassociated' => 'Unassociated',
        'label_associated' => 'Associated'
    )));

The above works just fine, but the values that are stored are unassociated to the choices list referenced above. I need to store the ids of the array retrieved as the values. Instead, the list that is retrieved is chronological and the ids are ignored.

Here's the schoolTable query:

 public function getUsersSchools($id){
          $q =Doctrine_Query::create()
             ->select('id')
             ->from('school')
             ->where('user_id = ?', $id)
             ->execute();
         return $q;
     }

Solution

  • If I understand your question correctly you would like to store associated school ids. Use the sfWidgetFormDoctrineChoice widget instead and it will work out of the box, as it using primary keys as ids.

    $query = Doctrine_Core::getTable('school')->queryForSelect($userId);
    $this->setWidget('schools', new sfWidgetFormDoctrineChoice(array(
      'model' => 'school',
      'query' => $query,
      'multiple' => true,
      'renderer_class' => 'sfWidgetFormSelectDoubleList', 
      'renderer_options' => array(
        'label_unassociated' => 'Unassociated',
        'label_associated' => 'Associated'
      ),
    )));
    $this->setValidator('schools', new sfValidatorDoctrineChoice(array(
      'model' => 'schoool',
      'query' => $query,
      'multiple' => true,
    )));
    
    // in SchoolTable class
    public function queryForSelect($userId)
    {
      return $this->createQuery('s')
        ->andWhere('s.user_id = ?', $userId)
      ;
    }
    

    If you has a proper schema (I presume the schools should be a many-to-many association), then the current from should has a schools_list field (properly defined in the generated base from) and then you can modify that field to be rendered by sfWidgetFormSelectDoubleList:

    $this->widgetSchema['schools_list']->setOption('renderer_class', 'sfWidgetFormSelectDoubleList');
    $this->widgetSchema['schools_list']->setOption('renderer_options', array(
      'label_unassociated' => 'Unassociated',
      'label_associated' => 'Associated'
    ));