Saturday, July 5, 2008

Adding to multiple tables from one form

Today I had a situation where I needed to add to the customer_addresses table when creating a new entry in the customers table. Fuse made this a simple exercise:

views/Customer/Customer-Edit.tmpl

<{IF message}>
<div style="margin-bottom: 8px; font-weight: bold; text-align:center; padding: 2px;">
<{message}>
</div>
<{/IF}>

<{form_script_tag}>
<{form_tag}>


<div style="margin-top: 6px;">First Name</div>
<div><{HTML/FormHelper::text_field('Customer', 'customer_f_name') }></div>

<div style="margin-top: 6px;">Last Name</div>
<div><{HTML/FormHelper::text_field('Customer', 'customer_l_name') }></div>

<div style="margin-top: 6px;">Email</div>
<div><{HTML/FormHelper::text_field('Customer', 'customer_email') }></div>

<div style="margin-top: 6px;">Address Line 1</div>
<div><{HTML/FormHelper::text_field('CustomerAddress', 'l1') }></div>

<div style="margin-top: 6px;">Address Line 2</div>
<div><{HTML/FormHelper::text_field('CustomerAddress', 'l2') }></div>

<div style="margin-top: 6px;">City</div>
<div><{HTML/FormHelper::text_field('CustomerAddress', 'city_name') }></div>


<div style="margin-top: 6px;">State</div>
<div><{HTML/FormOptionsHelper::Select_all('State', 'name', 'abbr', array('for_model' => 'CustomerAddress', 'for_field' => 'state_abbr')) }></div>

<div style="margin-top: 6px;">Zip</div>
<div><{HTML/FormHelper::text_field('CustomerAddress', 'zip_code') }></div>

<div>
<input type="submit" value="Save Changes" />
</div>

</form>

controllers/CustomerController.class.php

public function after_add() {

if ( $this->is_postback() ) {

FUSE::Require_model('CustomerAddress');

$address = new CustomerAddress();
$address->customer_id = $this->customer->id;
$address->add_from_form();

$this->redirect( 'customer/view/' . $this->model->id );
}

}


More information on Fuse can be found at http://www.phpfuse.net

No comments: