使用CakePHP 2填充动态选择框

时间:2013-10-02 16:36:53

标签: jquery ajax cakephp select

我一直试图用CakePHP和AJAX实现动态选择框。

查看:

index.ctp

<?php
echo $this->Html->script('jquery-1.6.3.min.js');
echo $this->Html->script('prototype', array('inline' => false));
echo $this->Js->writeBuffer();
?>    


<?php $this->Form->create('Supplier'); ?>
<?php echo $this->Form->input('categorie_id',array('type'=>'select','label' =>      false,'options'=>$categories,'class'=>'custom-dropdown__select custom-dropdown__select--white'));?>
<?php echo $this->Form->input('premieresc_id',array('type'=>'select','label' => false,'class'=>'custom-dropdown__select custom-dropdown__select--white'));?>
<?php $this->Form->end(); 
$this->Js->get('#CategorieId')->event('change', $this->Js->request( 
            array('controller' => 'suppliers', 'action' => 'getPremierescs'), 
            array( 
            'update' => '#PremierescId', 
            'async' => true, 
            'dataExpression' => true, 
            'method' => 'post', 
            'data' => $this->Js->serializeForm(array('isForm' => false, 'inline' => true)) 
            ))); 
?>

ajax_dropdown.ctp

 <?php foreach($premieres as $k => $v) { ?>
    <option value="<?php echo $k; ?>"><?php echo $v; ?></option>
 <?php } ?>

控制器:

  <?php
   class SuppliersController extends Controller {

var $name = 'Suppliers';
public $helpers = array('Js');
var $components = array('RequestHandler','Session');

public function index() {

    $this->loadModel('Premieresc');
    $this->loadModel('Categorie');

    $categories = $this->Categorie->find('list', array('fields' => array('Categorie.id','Categorie.categorie_label')));
    $premieres=array();
    $this->set(compact('premieres', 'categories'));

    $this->layout = 'ajax';
}

function getPremierescs() {
    $premieres = $this->Premieresc->find('list',array('conditions' => array('Premieresc.id_cat' => $this->request->data['Categorie']['id'],
    'fields' => array('Premieresc.id','Premieresc.level1_label'))));
    $this->set(compact('premieres'));       
    $this->layout = 'ajax';
    $this->render('/suppliers/ajax_dropdown', 'ajax');  
}

这些是模特:

<?php
class Premieresc extends AppModel {

var $name = 'Premieresc';

public $id;
public $level1_label;
public $belongsTo = array('Categorie' => array('className' => 'Categorie',
        'foreignKey' => 'id_cat'));

public $hasMany = array(
    'Deuxieme' => array('className' => 'Deuxiemesc',
        'foreignKey' => 'id_level1'));
 }
 ?>

 <?php
 class Categorie extends AppModel {

var $name = 'Categorie';

public $id;
public $categorie_label;
public $hasMany = array(
    'Premieresc' => array(
        'className' => 'Premieresc',
        'foreignKey' => 'id_cat'
    )
);
}
?>

0 个答案:

没有答案