CakePHP 3.6.11: обновить значение в таблице - PullRequest
0 голосов
/ 05 октября 2018

У меня есть следующие таблицы:

клиенты [идентификатор, имя, фамилия, телефон, текст, баланс, создано]

service_types [идентификатор, название, цена, длина, is_subscription, создан]

customer_service_types [id, customer_id, service_type_id, цена, создан]

Когда я добавляю новый customerServiceType для клиента, я хочу обновить balance изклиент соответственно использует заданное price значение customerServiceType.

Итак, вот что я попробовал:

CustomerServiceTypes/add.ctp:

<fieldset>
        <legend><?= __('Add Customer Service Type') ?></legend>
        <?php
            echo $this->Form->control('customer_id', ['options' => $customers]);
            echo $this->Form->control('service_type_id', ['options' => $serviceTypes]);
            echo $this->Form->control('price');
        ?>
    </fieldset>
    <?= $this->Form->button(__('Submit')) ?>
    <?= $this->Form->end() ?>

Model/Entity/CustomerServiceType.php:

class CustomerServiceType extends Entity
{
//On create a new CustomerServiceType then update the selected customer's balance
    public function addCustomerServiceType($data = array()){
        $this->create;
        $this->save($data);

        //update customer balance
        $customer = $this->Customers->get($data['customerid']);

        $this->Customer->updateAll(
            array('Customer.balance' => 'Customer.balance + ' . $data['price']),
            array('Customer.id' => $data['customerid'])
        );

        return true;
    }
}

Итак, в CustomerServiceTypesController.php я изменил add() следующим образом:

public function add($customerid = null)
    {
        $customerServiceType = $this->CustomerServiceTypes->newEntity();
        if ($this->request->is('post')) {
            $customerServiceType = $this->CustomerServiceTypes->patchEntity($customerServiceType, $this->request->getData());
            if ($this->CustomerServiceType->addCustomerServiceType($this->request->data)) {
                $this->Flash->success(__('The customer service type has been saved.'));

                return $this->redirect(['action' => 'index']);
            }
            $this->Flash->error(__('The customer service type could not be saved. Please, try again.'));
        }
        $customers = $this->CustomerServiceTypes->Customers->find('list', ['limit' => 200]);
        $serviceTypes = $this->CustomerServiceTypes->ServiceTypes->find('list', ['limit' => 200]);
        $this->set(compact('customerServiceType', 'customers', 'serviceTypes'));
    }

Но я получаю эту ошибку:

Вызов функции-члена addCustomerServiceType () для логического значения

И это уведомление:

Неопределенное свойство: CustomerServiceTypesController :: $ CustomerServiceType

1 Ответ

0 голосов
/ 05 октября 2018

Поскольку вы хотите, чтобы что-то произошло после сохранения данных, я думаю, вам лучше использовать событие Model.afterSave: https://book.cakephp.org/3.0/en/orm/table-objects.html#aftersave

В вашем контроллере

$this->CustomerServiceTypes->save($customerServiceType)

В вашем объекте таблицы CustomerServiceTypesTable.php

namespace App\Model\Table;

use Cake\ORM\Table;
use Cake\Event\Event;
use Cake\ORM\TableRegistry;
use ArrayObject;
use Cake\Datasource\EntityInterface;

class CustomerServiceTypesTable extends Table
{
    public function afterSave(Event $event, EntityInterface $entity, ArrayObject $options)
    {
        // only execute if the entity is new
        // if you want this to happen on edits too, remove this clause

        if ($entity->isNew()) {
            // get instance of the Customers table
            $customers = TableRegistry::getTableLocator()->get('Customers');

            $customer = $customers->get($entity->customerid);
            // do more stuff here
        }
    }
}
...