CakePHP 3.6.11:将所选值从下拉列表存储到数据库

CakePHP 3.6.11: store selected value from dropdown to database

我有这 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 字段?)

就像我告诉你的那样

像这样更改 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');
});