Alessandro Corradini
Alessandro Corradini

Reputation: 499

how to populate form select with zend framework 2 (2.3) and ajax request

i have 3 dynamic selects, state->country->city and i would concatenate them with an ajax request, but i can't do it :( without zf2 is more simple!

the function works fine if i set $idState manually within stateCountryCityAction (ex $idState = 1;) but dinamically doesn't work! why???? :(

this is my application\controller:

public function stateCountryCityAction()
    {
    $form1   = new StateCountryCityForm();
    $form1->get('State')->setOptions(array('value_options'=> $this->getState()));
    $request = $this->getRequest();

    if ($request -> isXmlHttpRequest()){
        $data = $request->getPost();  
        if (isset($data['state'])){
           $idState = $data['state'];
           $form1->get('Country')->setOptions(array('value_options'=> $this->getCountry($idState))); 
        }  

    }
    $viewmodel->setTerminal(true);
    $viewmodel->setVariables(array(
                'form1' => $form1,

    ));

    return $viewmodel;
}

this is the function than should populate the second select. it's within my application\controller below other functions:

public function getCountry($idState)
    {

    $dbAdapter = $this->getAdapter();
    $sql       = 'SELECT idCountry, Country FROM Country WHERE State_idState = '.$idState.' ORDER BY Country';
    $statement = $dbAdapter->query($sql);
    $result    = $statement->execute();

    $selectData = array('0' => '----- Tutta Italia -----');

    foreach ($result as $res) {
        $selectData[$res['idCountry']] = $res['Country'];
    }

    return $selectData;
}

this is my jquery function. i tried to alert the var state when the select change, and the output is correct! the jquery function returns the select's value.

$("select#State").change(function () {
         var state = $("select#State option:selected").attr('value');
         $.post("/zf-2tutorial/public/state-country-city", { state: state }, function () {

         });
     }); 

Upvotes: 1

Views: 821

Answers (1)

DTukans
DTukans

Reputation: 349

Try to get post value with this code $idState = $request->getPost('state');.

In code $data = $request->getPost(); $data will be an Zend\Stdlib\ParametersInterface - object and not array like in your sample.

Upvotes: 1

Related Questions