Jonathan
Jonathan

Reputation: 166

CakePHP drop down, selected item redirect to view for item

I would like to have the drop down list drugs, redirect to the view for the specific drug chosen. So say they click the drug "Acetamenophen" I want it to send them to the view for that drug. Can I do that without adding a submit button?

Code I have for the drop down:

<?php
echo $form->input('Drug.generic', array('type' => 'select', 'label' => 'Quick Select:',
  'empty' => 'Select', 'options' => $alldrugs)
);
?>

Index controller action(View the drop down is on)

  function index() {
    $this->set('drugs', $this->Drug->find('all'));
    $this->set('alldrugs', $this->Drug->find('list', array('fields' => array('id','generic'), 'order' => 'Drug.generic', 'recursive' => -1,)));
  }

Upvotes: 0

Views: 4122

Answers (3)

thecodeparadox
thecodeparadox

Reputation: 87073

You can store you root url in a js variable in default.ctp like following:

put this code within default.ctp <head></head> section.

<script>
  var _ROOT = "<?php echo $this->Html->url('/', true); ?>";
</script>

And within the <head> tag append this line before </head> end:

<?php echo $this->Html->script(array('jquery', 'drug_list')); ?>

Then use the _ROOT like following:

window.location = _ROOT + 'drugs/view/' + val;

Place jquery library and make a YOURNAME.js file in app/webroot/js folder and place following code with YOURNAME.js file.

YOURNAME is as you like

$(function() {
   $('#ID_OF_YOUR_SELECT_BOX').change(function() {   // replace the ID_OF_YOUR_SELECT_BOX with the id to your select box given by Cake
       var val = $(this).val();  // val is the drug id
       window.location = _ROOT + 'drugs/view/' + val;
    });
});

Upvotes: 2

nIcO
nIcO

Reputation: 5001

With a mix of jQuery and PHP, you can redirect directly to the action you want:

<?php
echo $form->input('Drug.generic', array('type' => 'select', 'label' => 'Quick Select:',
  'empty' => 'Select', 'options' => $alldrugs, 'id' => 'drug_select')
);
?>

$(document).ready(function(){

    $("#drug_select").change(function(){
        var drug_id = $(this).val();
        if(drug_id.length > 0)
        {
            window.location = "<?php echo Router::url(array('controller' => 'drugs', 'action' => 'view'), true) ?>/" + drug_id;
        }
    });

});

Upvotes: 0

pleasedontbelong
pleasedontbelong

Reputation: 20102

i'd put the select inside a form without the submit button, and add a onclick to the select (you don't actually need a whole framework for it):

<?php
echo $form->input('Drug.generic', array('type' => 'select', 'label' => 'Quick Select:',
  'empty' => 'Select', 'options' => $alldrugs, 'onchange'=>'this.form.submit();')
);
?>

of course in the controller you'd have to check the this->data and redirect the user to the correct page depending on the select, or if you dont want to redirect the user, just change the condition on the find().

Hope this helps,

Upvotes: 0

Related Questions