How to get data from different model for select?

不打扰是莪最后的温柔 提交于 2019-11-29 18:04:31

There are several different approaches you can take. Ultimately your Form has a dependency, which needs to be injected. I have written an in-depth blog-post about the three most common use-cases for Form-Dependencies for a Select-List.

My BlogPost covers the following scenarios:

  • Zend\Form\Element\Select via DbAdapter
  • Zend\Form\Element\Select via TableGateway
  • DoctrineModule\Form\Element\DoctrineObject via Doctrine2

Here i will demonstrate only the DbAdapter approach without much explanation. Please refer to my blogpost for the in-depth explanations.

public function formDbAdapterAction()
{
    $vm = new ViewModel();
    $vm->setTemplate('form-dependencies/form/form-db-adapter.phtml');

    $dbAdapter = $this->getServiceLocator()->get('Zend\Db\Adapter\Adapter');
    $form      = new DbAdapterForm($dbAdapter);

        return $vm->setVariables(array(
        'form' => $form
    ));
}

Then the respective Form Class:

class DbAdapterForm extends Form
{
    protected $dbAdapter;

    public function __construct(AdapterInterface $dbAdapter)
    {
        $this->setDbAdapter($dbAdapter);

        parent::__construct('db-adapter-form');

        $this->add(array(
            'name'    => 'db-select',
            'type'    => 'Zend\Form\Element\Select',
            'options' => array(
                'label'         => 'Dynamic DbAdapter Select',
                'value_options' => $this->getOptionsForSelect(),
                'empty_option'  => '--- please choose ---'
            )
        ));
    }

    // more later...

    // Also: create SETTER and GETTER for $dbAdapter!
}

And last but not least the DataProvider function:

public function getOptionsForSelect()
{
    $dbAdapter = $this->getDbAdapter();
    $sql       = 'SELECT t0.id, t0.title FROM selectoptions t0 ORDER BY t0.title ASC';
    $statement = $dbAdapter->query($sql);
    $result    = $statement->execute();

    $selectData = array();

    foreach ($result as $res) {
        $selectData[$res['id']] = $res['title'];
    }

    return $selectData;
}

My use is like that:

Class Useful{
/**
 * All languages
 * @return array 
 */
public static function getLanguages(){
  return array(
    'fr_DZ'=>'Algeria - Français',
    'es_AR'=>'Argentina - Español',
    'en_AU'=>'Australia - English',
    'nl_BE'=>'België - Nederlands',
    'fr_BE'=>'Belgique - Français',
    'es_BO'=>'Bolivia - Español',
    'bs_BA'=>'Bosna i Hercegovina - Hrvatski',
  ...
  );
 }
}

After I use like that:

$this->add(array(
  'type' => 'Zend\Form\Element\Select',
  'name' => 'languages',
  'attributes'=>array(
     'multiple'=>"multiple",
   ),
   'options'       => array(
     'label'             => 'My languages I speak',
     'description'       => '',
     'value_options'     => Useful::getLanguages()
    ),
 ));
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!