CakePHP 3.6.11:将下拉列表中的选定值存储到数据库中

时间:2018-09-27 13:55:58

标签: php cakephp cakephp-3.6

我有以下3张桌子:

客户:

customerstable

服务:

servicestable

客户服务:

customerservicestable

CustomerservicesTable.php中具有这种关系:

$this->belongsTo('Customers')
            ->setForeignKey('customerid');

$this->belongsTo('Services')
            ->setForeignKey('serviceid');

Template\Customerservices\add.ctp中,我有一个带有下拉菜单和数字字段的表单:

<div class="customerservices form large-9 medium-8 columns content">
    <?= $this->Form->create($customerservice) ?>
    <fieldset>
        <legend><?= __('Add transaction') ?></legend>
        <?php
            echo $this->Form->input('Transaction type',array('options' => $servicesList));
            echo $this->Form->control('price');
        ?>
    </fieldset>
    <?= $this->Form->button(__('Submit')) ?>
    <?= $this->Form->end() ?>
</div>

Controller\CustomerservicesController.php中:

public function add($customerid = null)
    {

        $customerservice = $this->Customerservices->newEntity();
        if ($this->request->is('post')) {
            $customerservice->customerid = $customerid;
            $customerservice->serviceid = //get selection from dropdown
            if ($this->Customerservices->save($customerservice)) {
                $this->Flash->success(__('The customerservice has been saved.'));

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

        $servicesList = TableRegistry::getTableLocator()->get('Services')->find('list');
        $this->set(compact('servicesList'));
    }

如何保存注释以保存在下拉控件中选择的serviceid

(第二个问题,是否可能根据下拉菜单选择隐藏price字段?)

1 个答案:

答案 0 :(得分:0)

就像我告诉你couple of minutes ago

像这样更改input

echo $this->Form->input('transaction_type',array('type'=>'select','options' => $servicesList));

在您的Controller中:

public function add($customerid = null)
{
    …
    $customerservice->serviceid = $this->request->getData('transaction_type');
    …
}

根据下拉列表中的选择隐藏price字段似乎是客户端的一项工作,可以使用JavaScript来完成。例如在jQuery中:

$('#transaction_type').on('change', function() {
    // hide element with ID #price if value of select with ID #transaction_type is `holymoly`
    // and show element if value is anything else
    $('#price').toggle(this.value === 'holymoly');
});