【问题标题】:HOW TO DISPLAY DATA IN DROP DOWN LIST FROM OTHER TABLE IN CAKEPHP 3?如何在 CAKEPHP 3 中其他表的下拉列表中显示数据?
【发布时间】:2016-09-12 05:06:15
【问题描述】:

我有两张桌子:

departamento(“地区”的西班牙语)
provincia(“省”的西班牙语)

“departamento”有三个字段:

id_departamento
departamento(地区名称)
presidente(州长)

“provincia”有四个字段:

id_provincia
id_departamento(外键)
provincia(省名)
gobernador(省长)

我使用命令行(模型、控制器和模板)生成 cakephp 代码。

但是,在生成的视图中,显示插入输入 id,我不想要它 --> SCREEN CAPTURE

当我要添加一个新省份时,我想用 地区名称 显示和替换地区 ID 字段,如下拉列表

PROVINCIACONTROLLER.PHP

<?php
namespace App\Controller;

use App\Controller\AppController;

/**
 * Provincia Controller
 *
 * @property \App\Model\Table\ProvinciaTable $Provincia
 */
class ProvinciaController extends AppController
{

    /**
     * Index method
     *
     * @return \Cake\Network\Response|null
     */
    public function index()
    {
        $provincia = $this->paginate($this->Provincia);

        $this->set(compact('provincia'));
        $this->set('_serialize', ['provincia']);
    }

    /**
     * View method
     *
     * @param string|null $id Provincium id.
     * @return \Cake\Network\Response|null
     * @throws \Cake\Datasource\Exception\RecordNotFoundException When record not found.
     */
    public function view($id = null)
    {
        $provincium = $this->Provincia->get($id, [
            'contain' => []
        ]);

        $this->set('provincium', $provincium);
        $this->set('_serialize', ['provincium']);
    }

    /**
     * Add method
     *
     * @return \Cake\Network\Response|void Redirects on successful add, renders view otherwise.
     */
    public function add()
    {
        $provincium = $this->Provincia->newEntity();
        if ($this->request->is('post')) {
            $provincium = $this->Provincia->patchEntity($provincium, $this->request->data);
            if ($this->Provincia->save($provincium)) {
                $this->Flash->success(__('The provincium has been saved.'));

                return $this->redirect(['action' => 'index']);
            } else {
                $this->Flash->error(__('The provincium could not be saved. Please, try again.'));
            }
        }
        $this->set(compact('provincium'));
        $this->set('_serialize', ['provincium']);
    }

    /**
     * Edit method
     *
     * @param string|null $id Provincium id.
     * @return \Cake\Network\Response|void Redirects on successful edit, renders view otherwise.
     * @throws \Cake\Network\Exception\NotFoundException When record not found.
     */
    public function edit($id = null)
    {
        $provincium = $this->Provincia->get($id, [
            'contain' => []
        ]);
        if ($this->request->is(['patch', 'post', 'put'])) {
            $provincium = $this->Provincia->patchEntity($provincium, $this->request->data);
            if ($this->Provincia->save($provincium)) {
                $this->Flash->success(__('The provincium has been saved.'));

                return $this->redirect(['action' => 'index']);
            } else {
                $this->Flash->error(__('The provincium could not be saved. Please, try again.'));
            }
        }
        $this->set(compact('provincium'));
        $this->set('_serialize', ['provincium']);
    }

    /**
     * Delete method
     *
     * @param string|null $id Provincium id.
     * @return \Cake\Network\Response|null Redirects to index.
     * @throws \Cake\Datasource\Exception\RecordNotFoundException When record not found.
     */
    public function delete($id = null)
    {
        $this->request->allowMethod(['post', 'delete']);
        $provincium = $this->Provincia->get($id);
        if ($this->Provincia->delete($provincium)) {
            $this->Flash->success(__('The provincium has been deleted.'));
        } else {
            $this->Flash->error(__('The provincium could not be deleted. Please, try again.'));
        }

        return $this->redirect(['action' => 'index']);
    }
}

PROVINCIATABLE.PHP

<?php
namespace App\Model\Table;

use Cake\ORM\Query;
use Cake\ORM\RulesChecker;
use Cake\ORM\Table;
use Cake\Validation\Validator;

/**
 * Provincia Model
 *
 * @method \App\Model\Entity\Provincium get($primaryKey, $options = [])
 * @method \App\Model\Entity\Provincium newEntity($data = null, array $options = [])
 * @method \App\Model\Entity\Provincium[] newEntities(array $data, array $options = [])
 * @method \App\Model\Entity\Provincium|bool save(\Cake\Datasource\EntityInterface $entity, $options = [])
 * @method \App\Model\Entity\Provincium patchEntity(\Cake\Datasource\EntityInterface $entity, array $data,

数组 $options = []) * @method \App\Model\Entity\Provincium[] patchEntities($entities, array $data, array $options = []) * @method \App\Model\Entity\Provincium findOrCreate($search, callable $callback = null) */ ProvinciaTable 类扩展表 {

    /**
     * Initialize method
     *
     * @param array $config The configuration for the Table.
     * @return void
     */
    public function initialize(array $config)
    {
        parent::initialize($config);

        $this->table('provincia');
        $this->displayField('id_provincia');
        $this->primaryKey('id_provincia');
    }

    /**
     * Default validation rules.
     *
     * @param \Cake\Validation\Validator $validator Validator instance.
     * @return \Cake\Validation\Validator
     */
    public function validationDefault(Validator $validator)
    {
        $validator
            ->integer('id_provincia')
            ->allowEmpty('id_provincia', 'create')
            ->add('id_provincia', 'unique', ['rule' => 'validateUnique', 'provider' => 'table']);

        $validator
            ->integer('id_departamento')
            ->requirePresence('id_departamento', 'create')
            ->notEmpty('id_departamento');

        $validator
            ->requirePresence('provincia', 'create')
            ->notEmpty('provincia');

        $validator
            ->requirePresence('gobernador', 'create')
            ->notEmpty('gobernador');

        return $validator;
    }

    /**
     * Returns a rules checker object that will be used for validating
     * application integrity.
     *
     * @param \Cake\ORM\RulesChecker $rules The rules object to be modified.
     * @return \Cake\ORM\RulesChecker
     */
    public function buildRules(RulesChecker $rules)
    {
        $rules->add($rules->isUnique(['id_provincia']));

        return $rules;
    }
}

PROVINCIA.PHP

<?php
namespace App\Model\Entity;

use Cake\ORM\Entity;

/**
 * Provincium Entity
 *
 * @property int $id_provincia
 * @property int $id_departamento
 * @property string $provincia
 * @property string $gobernador
 */
class Provincium extends Entity
{

    /**
     * Fields that can be mass assigned using newEntity() or patchEntity().
     *
     * Note that when '*' is set to true, this allows all unspecified fields to
     * be mass assigned. For security purposes, it is advised to set '*' to false
     * (or remove it), and explicitly make individual fields accessible as needed.
     *
     * @var array
     */
    protected $_accessible = [
        '*' => true,
        'id_provincia' => false
    ];
}

ADD.CTP(添加省份)

<nav class="large-3 medium-4 columns" id="actions-sidebar">
    <ul class="side-nav">
        <li class="heading"><?= __('Actions') ?></li>
        <li><?= $this->Html->link(__('List Provincia'), ['action' => 'index']) ?></li>
    </ul>
</nav>
<div class="provincia form large-9 medium-8 columns content">
    <?= $this->Form->create($provincium) ?>
    <fieldset>
        <legend><?= __('Add Provincium') ?></legend>
        <?php
            echo $this->Form->input('id_departamento');
            echo $this->Form->input('provincia');
            echo $this->Form->input('gobernador');
        ?>
    </fieldset>
    <?= $this->Form->button(__('Submit')) ?>
    <?= $this->Form->end() ?>
</div>

感谢您的帮助

【问题讨论】:

  • 请禁用大写字母
  • 你的意思是你想要一个下拉列表来填充“DEPARTAMENTO”表中的值?使用值 ID_DEPARTAMENTO 和文本 DEPARTAMENTO (NAME OF REGION)?..请禁用大写字母并正确提及您的表和模型的名称。
  • 我想要视图,我想要一个显示区域名称值的下拉列表,但是,在数据库的插入查询中,插入带有区域名称“id_departamento”的行,因为表“provincia”具有“id_departamento”作为外键引用 epartamento(id_departamento)...
  • 我的问题与此类似 --> stackoverflow.com/questions/30947323/…

标签: php mysql cakephp-3.0


【解决方案1】:

如果您想要一个部门的下拉列表,您需要使用find('list') 获取它们并将其设置到模板中。

考虑到您的表名称是 Departmento,并且您想要填充值 id_departamento 和文本 departamento,请尝试以下操作:

/* Controller Code */
public function add()
{
    $provincium = $this->Provincia->newEntity();
    if ($this->request->is('post')) {
       /* Other code */
    }
    /* Modified code starts */
    $departmento = $this->Departmento->find('list', [
        'keyField'   => 'id_departamento',
        'valueField' => 'departmento'
    ]);
    $this->set(compact('departmento'));
    /* Modified code ends*/
    $this->set(compact('provincium'));
    $this->set('_serialize', ['provincium']);
}

/* Template code */

 echo $this->Form->select('id_departamento', $departmento, [
     'empty' => 'Departmento'
 ]);

【讨论】:

  • 是的,它是“departamento”(英语中的 region = 西班牙语中的 departamento)..
  • 根据您的模型/表字段名称,您可能需要进行一些修改。但总的来说,这是您需要遵循的想法才能实现您想要实现的目标。
  • 是的。我想要视图,我想要一个显示区域名称值的下拉列表(表“departamento”、字段“departamento”或(名称)),但是,在数据库的插入查询中,插入带有“id_departamento”的行区域名称,因为表“provincia”有“id_departamento”作为外键引用departamento(id_departamento)......对不起,我的英文写作不好......
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-12-05
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多