how to populate a second form select when selected first one

For programming and general questions on Zend Framework

how to populate a second form select when selected first one

Postby joel8233 on Tue May 23, 2017 7:52 pm

I have two dynamically created form element select:

class quickSearchCarForm extends Form{
The first select element is for the vehicles maker

$makerSelect = new Element\Select('maker');
$makerSelect->setLabel('Maker and Model');
$list = $this->vehiclesManager->getArrayMakers(1);
$makerSelect->setValueOptions($list);
$makerSelect->setAttributes(['onchange' => 'FillSelectModels(this.value)']);
$makerSelect->setEmptyOption('Select Maker..');
$this->add($makerSelect);
Second select is for the models

$modelSelect = new Element\Select('model');
$modelSelect->setEmptyOption('Select Model...');
$this->add($modelSelect);
}
I have the following function on my controller that should fill second Element\Select when I select first one.

public function getModelsArray($idMaker) {
$EntityModelsList = $this->getEntityModelsList($idMaker);
$oArray = [];
foreach ($EntityModelsList as $value) {
$id = $value->getID();
$model = $value->getModel();
$oArray[$id] = $model;
}
return $oArray;
}
I'm thing I should do it using JavaScript but I don't know how

function FillSelectModels(idMaker){
if(idMaker !== "")
{
var Myarray = "<?= echo $this->controller->getArrayModelos(idMaker,1); ?>";
alert(Myarray);


}
};
Do you have any idea about how to do it?
joel8233
 
Posts: 4
Joined: Tue May 23, 2017 7:49 pm

Re: how to populate a second form select when selected first

Postby mehm8471 on Tue May 30, 2017 4:42 pm

Yes, you will create FillSelectModels() javascript function, send an AJAX request to the server by using a predefined route that calls a new action in your controller which is supposed to return JsonModel contains the values for the select object.

This is how it is done in theory.

Please let me know if you use jQuery in your project (if not then I suggest start using a javascript framework - preferably jQuery as I mentioned it), then I'll try to provide more information.
Suat
smozgur.com
mehm8471
 
Posts: 23
Joined: Sat Jun 21, 2014 11:39 pm

Re: how to populate a second form select when selected first

Postby joel8233 on Sun Jul 02, 2017 8:37 pm

Yes I'm triyng to use JQuery but with no success.

My Action:
public function indexAction()
{

$formCar =new quickSearchCarForm($this->veiculosManager);
$request = $this->getRequest();
$response = $this->getResponse();
if ($request->isXmlHttpRequest()) {
$idMarca = $this->params()->fromRoute('id');
$arrayModelos = $this->veiculosManager->getArrayModelos($idMarca, Veiculo::Carro); //Metodo ja testado e a funcionar. retorna um ['idmodelo' => 'modelo' ]
return $response->setContent(json_encode($arrayModelos));

}
}


*******On My View I've Tried with JQuery but with no success

function getModelos(id) {
$.ajax({
type:'POST',
dataType: 'json',
url:'/index/'+id,
data: data,
success: function(data){
console.log(data);
$('#modelofield').html(data);
}
});
}

------I've tried with AJAX, but the only thing that happens is: the values of other form elements goes to my #modelfield (ex: makers, year, fuel..)

function getModelos(id) {
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (this.readyState === 4 && this.status === 200) {
document.getElementById("modelofield").innerHTML = this.responseText;
}
};
xhttp.open("POST", "index/" + id, true);
xhttp.send();
}
joel8233
 
Posts: 4
Joined: Tue May 23, 2017 7:49 pm

Re: how to populate a second form select when selected first

Postby joel8233 on Sun Jul 02, 2017 8:41 pm

mehm8471 wrote:Yes, you will create FillSelectModels() javascript function, send an AJAX request to the server by using a predefined route that calls a new action in your controller which is supposed to return JsonModel contains the values for the select object.

This is how it is done in theory.

Please let me know if you use jQuery in your project (if not then I suggest start using a javascript framework - preferably jQuery as I mentioned it), then I'll try to provide more information.


Yes I'm triyng to use JQuery but with no success.

My Action:
Code: Select all
public function indexAction()
    {
   
    $formCar =new quickSearchCarForm($this->veiculosManager);
     $request = $this->getRequest(); 
     $response = $this->getResponse();
        if ($request->isXmlHttpRequest()) {
            $idMarca = $this->params()->fromRoute('id');
            $arrayModelos = $this->veiculosManager->getArrayModelos($idMarca, Veiculo::Carro);  //Metodo ja testado e a funcionar. retorna um ['idmodelo' => 'modelo' ]
            return $response->setContent(json_encode($arrayModelos));
           
        }
    }



*******On My View I've Tried with JQuery but with no success

Code: Select all
  function getModelos(id) {
                $.ajax({
                    type:'POST',
                    dataType: 'json',
                    url:'/index/'+id,
                    data: data,
                    success: function(data){
                        console.log(data);
                        $('#modelofield').html(data);
                    }
                });
                }


------I've tried with AJAX, but the only thing that happens is: the values of other form elements goes to my #modelfield (ex: makers, year, fuel..)

Code: Select all
function getModelos(id) {
                var xhttp = new XMLHttpRequest();
                xhttp.onreadystatechange = function() {
                  if (this.readyState === 4 && this.status === 200) {
                   document.getElementById("modelofield").innerHTML = this.responseText;
                  }
                };
                xhttp.open("POST", "index/" + id, true);
                xhttp.send();
                }


OBS: I'm Using Zend Framework 3
joel8233
 
Posts: 4
Joined: Tue May 23, 2017 7:49 pm

Re: how to populate a second form select when selected first

Postby joel8233 on Sun Jul 02, 2017 8:51 pm

..
joel8233
 
Posts: 4
Joined: Tue May 23, 2017 7:49 pm

Re: how to populate a second form select when selected first

Postby mehm8471 on Wed Jul 05, 2017 1:33 am

Joel,

*** I am sending this by hoping it might also help others ****

I assume $arrayModelos is the array contains the models as key/value pairs that you’d like to load dynamically and it is returned correctly by your model.

Don’t use json_encode, have Zend do that for you, there is a wonderful module zend-json and view strategy for this purpose.

What I do is creating a JsonModel object in the action module that I use for Ajax calls and return it (instead of what you return) : I name the data array (key/value pair) as ‘modelos'

Code: Select all
        return new JsonModel([
            'modelos' => $arrayModelos,
        ]);


To be able to use JsonModel:

1- need to install zend-json

Code: Select all
   composer require zendframework/zend-json


2- import the module in the controller class:

Code: Select all
   use Zend\View\Model\JsonModel;


3- add 'ViewJsonStrategy' in your module.config.php

Code: Select all
    'view_manager' => [
      // ...
        'strategies' => [
            'ViewJsonStrategy',
        ],
    ],


(Note: It is for another purpose but I explain how to do this at: https://smozgur.com/blog/zend-framework/amazon-polly-service-with-zend-framework/ - JsonModel usage / setting is explained at the beginning of the post)

This was the controller side. Then I can make some changes in your javascript function to make it work:

Code: Select all
      function getModelos(id) {
         $.ajax({
            type:'POST',
            dataType: 'json',
            url:’/index/‘ + id,
            success: function(response){
               $('#modelofield').empty();
               $.each(response.modelos, function(id, modelo) {
                      $('#modelofield').append($('<option>', {
                             value: id,
                             text: modelo
                      }));
               });
            }
         });
      }


Please note the response.modelos is the array value of the models I named as ‘modelos’ when I create my JsonModel in the controller action. Since it is key / value pair, I used $.each method in jquery to update the select object content.

I hope this helps.
Suat
smozgur.com
mehm8471
 
Posts: 23
Joined: Sat Jun 21, 2014 11:39 pm


Return to Zend Framework

Who is online

Users browsing this forum: Google [Bot] and 3 guests

cron