我在数据库中有一个user_addresses
表来存储用户的地址。由于用户可以存储多个地址,但只有一个地址为Primary of Default Address
。要将地址设置为Primary Address
,表格的列default_flag
为1 if primary else 0 for non primary
。
现在,因为用户只能拥有一个主要地址,以后可以随时更改。为此,我列出了default_flag != 1
的所有地址以及旁边的按钮,将其设置为primary address
。当用户点击该按钮时,地址设置为主要地址,之前的主要地址default_flag
设置为0
。
我试过这样做。
我创建了一个postButton
,其中两个键传递给updatePrimaryAddress
动作,一个是要设置为主要地址的id,另一个是已经是主要地址的id。 / p>
<?= $this->Form->postButton(__('Choose'), ['controller' => 'UserAddresses', 'action' => 'updatePrimaryAddress', $nonPrimaryAddress->id, $primaryAddressId], ['class' => 'btn btn-success pull-left']) ?>
在UserAddressesController
<?php
namespace App\Controller;
use App\Controller\AppController;
use Cake\ORM\TableRegistry;
/**
* UserAddresses Controller
*
* @property \App\Model\Table\UserAddressesTable $UserAddresses
*/
class UserAddressesController extends AppController
{
public function updatePrimaryAddress($id = null, $primaryAddress = null)
{
$userAddresses = TableRegistry::get('UserAddresses');
$primaryAddress = $userAddresses->get($primaryAddress);
$primaryAddress->default_flag = 0;
$userAddresses->save($primaryAddress);
$address = $userAddresses->get($id);
$address->default_flag = 1;
$userAddresses->save($address);
return $this->redirect($this->referer());
}
}
点击按钮,页面重新加载,但数据库中没有数据更改。
答案 0 :(得分:1)
为什么在甚至没有阅读动作中的数据时使用postButton?
您可以使用简单的链接:
$this->Html->link(__('Choose'), [
'controller' => 'UserAddresses',
'action' => 'updatePrimaryAddress',
$nonPrimaryAddress->id, // you don't need this
$primaryAddressId
],
['class' => 'btn btn-success pull-left']
);
但是您甚至不需要像在数据库中那样发送有关旧地址的信息。
public function updatePrimaryAddress($address_id)
{
// I suppose you have authenticated you user
// so let's retrieve his id
$user_id = $this->Auth->User('id')
// now I set the address as default
// but only if it belongs to that user
$rows_affected = $this->userAddresses->UpdateAll(
['default_flag' => 1],
[
'user_id' => $user_id,
'id' => $address_id
]);
// now I set all the other addresses as not default
// but only if I have successfully changed the default address
// and just for that one user
if($rows_affected > 0)
{
$this->userAddresses->UpdateAll(
['default_flag' => 0],
[
'user_id' => $user_id,
'id !=' => $address_id
]);
}
else
{
$this->Flash->warning("Seems you're trying to switch to a non existing address or to change other's user address");
}
return $this->redirect($this->referer());
}