开发者

cakephp habtm relationships with input rather than select box?

开发者 https://www.devze.com 2022-12-18 03:16 出处:网络
I\'m creating a form in cakep开发者_运维百科hp that has a typical HABTM relationship. Let\'s say that I\'m developing an order form with a coupon code. From a logic point of view, I need to accept a t

I'm creating a form in cakep开发者_运维百科hp that has a typical HABTM relationship. Let's say that I'm developing an order form with a coupon code. From a logic point of view, I need to accept a text-entry for the coupon code, so the incoming data would not be the proper primary key, but rather a different field.

I would then need to validate that data, and retrieve the proper primary key id, and then update the orders_coupons table with that coupon_id, and order_id.

When using a select box the value would always be the proper coupon_id, but where is the appropriate location for me to put the logic to handle this? Should I modify the data using beforeSave?


your question isn't very clear b/c it sounds like you can both specify the coupon via a select box or in just a free form text box.

My inclination is to add a new method to the Model that would update the record with the "human readable key". So the function would first read the coupon_id from the DB, and then do the update.


As you said, you'll just have to look up the coupon id...

// assuming $data looks like:
// array('Order' => array(...), 'Coupon' => array('code' => ...))

$coupon_id = $this->Order->Coupon->field('id', array('code' => $data['Coupon']['code']));

if (!$coupon_id) {
    // user put in a non-existing coupon code, punish him!
} else {
    $data['Order']['coupon_id'] = $coupon_id;
    $this->Order->save($data);
}


If I get this correct, this is pretty much the same as tagging?! (There is a text input box for habtm items and the string is submitted to the controller without the ids).

If so, I would recommend to split the processing. Submit the data to the controller and then pass the coupon-string to a proper function in the coupon-model, that gets the coupon-ids (saves new items) and returns them back to the controller to save the complete habtm-data.

0

精彩评论

暂无评论...
验证码 换一张
取 消