tags:

views:

120

answers:

3

I'm creating a form in cakephp 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?

A: 

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.

mlathe
Essentially, users type in a coupon code a text box (no select because they shouldn't be able to choose the coupon code). When they manually type in the code, the model would need to know that it's not an ID coming for the HABTM relationship, so it will need to look up the entered coupon code, determine the true primary key, and save *that* to the habtm table.
BotskoNet
right. So you would create a method in the Model like setCouponCode(code), it would assume you always passed in a human readable coupon code (after all how would a human know the coupon_id?), and use that to find the real coupon_id, and save it to the HABTM.
mlathe
A: 

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.

harpax
A: 

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);
}
deceze