zf2 form: populate select field with data coming from database

最后都变了- 提交于 2019-12-12 13:55:32

问题


I'm learning zf2 and I'm facing a problem involving 2 (eventually more) modules working together. Note, I've carefully read this post (and the related one) which helped me a lot. I'm going to explain a bit the problem:

  • Using the first module (FrOption) an administrator can manage website form options. All options are stored in a db table like this:

id|field_name|field_value
1|country|germany|
2|country|france|
3|gender|Male|
4|gender|Female|
5|tipo|Car|
6|tipo|Fly|
...

  • In my module (FrItem) I've built a form which needs some "field_name" fields. My "item" table is the following:

id|name|id_tipo|
1|Fiat|5|
2|Lufthansa|6|
3|Ford|5|
4|Air France 6|
...

(id_tipo is an option FK)

Also consider:

  • My entity has the "tipo" property, setter + getter
  • I've built an ItemHydrator to "map" id_tipo db field to "tipo" entity property
  • As a test, I've added this field in my form class and everything works fine both in view and edit mode:

    $this->add(
    'type' => 'Zend\Form\Element\Select',
    'name' => 'id_tipo',
    'options' => array (
        'label' => 'Tipo', 
        'empty_option' => 'Select',
        'value_options' => array ('5' => 'Car', '6' => 'Fly' ) )
    

    );

Now i want to "link" the two modules: value_options should be a dynamic array coming from FrOption so I'm looking for the the best way to accomplish this requirement.

I thought one solution could be something like this:

  1. Add to my FrOption/src/FrOption/Service/FrOption.php Service class the getOptionByName($fieldName) method
  2. In FrItem/Module.php retrieve the Service, then the data using getOptionByName and finally inject all into the Form.

Could this be a wise and working solution? What do you thing about it also in terms of performance (option table could grow)? If any, what kind of solution have you used to solve a similar problem?

Thanks


回答1:


This can be done easily by following the below 2 steps in Zend Framework2 Step 1.

add The instance of the adapter what instantiating form class in the controller action

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

Step 2 in your form

namespace Test\Form;

use Zend\Form\Form;
use Zend\Db\Adapter\AdapterInterface;
use Zend\Db\Adapter\Adapter;
class TestForm extends Form
{
    protected $adapter;
    public function __construct(AdapterInterface $dbAdapter)
    {
        $this->adapter =$dbAdapter;
                parent::__construct("Test Form");
        $this->setAttribute('method', 'post');
                //your select field
$this->add(array(
                'type' => 'Zend\Form\Element\Select',
                'name' => 'name',
                'tabindex' =>2,
                'options' => array(
                        'label' => 'Author',
                        'empty_option' => 'Please select an author',
                        'value_options' => $this->getOptionsForSelect(),
                )
        ));

                // another fields

}
       public function getOptionsForSelect()
    {
        $dbAdapter = $this->adapter;
        $sql       = 'SELECT id,name  FROM newsauthor where active=1 ORDER BY sortorder ASC';
        $statement = $dbAdapter->query($sql);
        $result    = $statement->execute();

        $selectData = array();

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

}

And here you go you are ready to rock.I hope it helps you




回答2:


Try:
// add code on controller
$arrTipoData = array();
$tipoResults = array('5' => 'Car', '6' => 'Fly',);  // this part change your database value
foreach ($tipResults as $key => $val) {
$arrTipoData[$key] = $va;
}

$arrGenderData = array();
$genderResults = array('3' => 'Male', '4' => 'Female',);  // this part change your database value
foreach ($genderResults as $key => $val) {
$arrGenderData[$key] = $va;
}
$dataParams['idTipo'] = $arrTipoData;
$dataParams['gender'] = $arrGenderData;
$form = new UserForm($dataParams);

 <?php
namespace Register\Form;
use Zend\Form\Form;
use Zend\Form\Element;


class UserForm extends Form
{
    protected $portalTable;

    public function __construct($params = array())
    {   $name = isset($params['name'])?$params['name']:'';
        parent::__construct('user');
       $this->setAttribute('method', 'post');
        $this->setAttribute('enctype', 'multipart/form-data');

    $idTipo = (isset($params['idTipo']) && count($params['idTipo']) > 0)?$params['idTipo']:array();
        $this->add(array(
                'type' => 'Select',
                'name' => 'id_tipo',
                'options' => array(
                        'label' => 'Tipo',
                        'empty_option' => 'Select Tipo',
                        'value_options' => $idTipo,

                )
        ));

        $gender = (isset($params['gender']) && count($params['gender']) > 0)?$params['gender']:array();
        $this->add(array(
                'type' => 'Select',
                'name' => 'gender_id',
                'options' => array(
                        'label' => 'Gender',
                        'empty_option' => 'Select',
                        'value_options' => $gender,

                )
        ));

    }
}


来源:https://stackoverflow.com/questions/15551188/zf2-form-populate-select-field-with-data-coming-from-database

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!