Selected dependens or drop down box

hello friends, I’m new programmer in CAKEPHP V 3, and tried to make a dependent select, region, comuna, but I can not get it, try to do it this way but cakephp 3 in this version does not accept it.

$this->Js->get(’#region_id’)->event( ‘change’, $this->Js->request(
array(‘controller’ => ‘Institutions’, ‘action’ => ‘get_by_region’),
array(
‘update’ => ‘#comuna_id’,
‘async’ => true,
‘dataExpression’ => true,
‘method’ => ‘post’,
‘data’ => $this->Js->serializeForm(array(‘isForm’ => true, ‘inline’ => true)))));

?>

i need you help please.

I do it like that:

function on controller:

    public function municipios() {

    $this->viewBuilder()->layout('ajax');
    $this->LoadModel('Municipios');
    $subregion = $this->request->data['subregion_id'];
    //$subregion = 2;

    $municipios = $this->Municipios->find('list',[
        'limit' => 200,

        'conditions' => ['Municipios.subregion_id' => $subregion],
        'contain' => ['Subregiones']

       ]);

    $this->set(compact('municipios'));
    $this->set('_serialize', 'municipios');

}

template:

<option value="">Seleccione el Municipio</option>
<?php foreach ($municipios as $key => $value): ?>
<option value="<?php echo $key; ?>"><?php echo $value; ?></option>
<?php endforeach;

jquery :

$(document).ready(function () {
    $("#subregion-id").bind("change",
    function (event) {
      $.ajax({
    async:true,
    data: $("#subregion-id").serialize(),
    dataType:"html",
    beforeSend: function (xhr) { // Add this line
        xhr.setRequestHeader('X-CSRF-Token', $('[name="_csrfToken"]').val());
    },
    success:
    function (data, textStatus) {
      $("#municipio-id").html(data);
      },
      type:"post", url:"\/lavaderos\/municipios"});
  return false;
      });
  });

If you have any problem, let me know

1 Like

Hello Jose. I tried your code but the response (“data”) is empty.

My code is:

Controller:

<code>

public function categories() {

    $this->autoRender = false;

    $this->viewBuilder()->layout('ajax');
    
    $productTypeId = $this->request->data['product_type_id'];

    $categoriesAux = TableRegistry::get('Categories', ['table' => 'categories']);                            
    $categories = $categoriesAux->find('list');

    $this->set(compact(('categories')));
    $this->set('_serialize', 'categories');   

}

Template:

Tipo de Producto: <?php echo $this->Form->select('product_type_id', $productTypes,['id' => 'productTypes', 'empty' => 'Seleccione','class' => 'form-control', 'label' => false]) ?>

Categoría: <?php echo $this->Form->select('category_id', $categories,['id' => 'categories', 'empty' => 'Seleccione','class' => 'form-control', 'label' => false]) ?>

script>
(document).ready(function () {
("#productTypes").bind("change", function (event) { .ajax({
async:true,
data: ("#productTypes").serialize(), dataType:"html", beforeSend: function (xhr) { // Add this line xhr.setRequestHeader('X-CSRF-Token', (’[name="_csrfToken"]’).val());
},
success:
function (data, textStatus) {
alert(data);
$("#categories").html(data);
},
type:“post”, url:"/sico/admin/products/categories"});
return false;
});
});
/script>

Any help?

Regards
Emiliano

using Request handler:

    public function initialize(): void
    {
        parent::initialize();

        $this->loadComponent('RequestHandler');
    }

    public function test()
    {
        $this->RequestHandler->renderAs($this, 'json');
        $var = ['a', 'b', 'c'];

        $this->set(compact('var'));
        $this->set('_serialize', 'var');
    }

or without:

public function test()
    {
        $var = ['a', 'b', 'c'];
        $this->response = $this->response->withType('json');
        $this->response->getBody()->write(json_encode($var));
        
        return $this->response;
    }
1 Like

thanks!

I changed my code too…

success:
              function (data, textStatus) {
                
                // se limpia el combo
                $("#categories").html(''); 
                $('#categories').append($('<option>').text("Seleccione").attr('value', -1));

                // si hay datos para mostrar
                if (data.length){
                  $.each(JSON.parse(data), function(i, optionHtml){
                    //console.log(i);
                    //console.log(optionHtml);
                    $('#categories').append($('<option>').text(optionHtml).attr('value', i));
                  });
                }

              },