1

I am new to Object Model Mapping and just read the documentation of the CodeIgniter DataMapper. I have tried the examples and I am quite impressed in how little time one can achive a lot.

But I don't seem to get one problem solved:

Lets say I have two tables: customer and address. A customer can have many addresses but am address only one customer.

Now, I have a registration form where a new customer has to enter his personal data which is stored in the customer table and his address which is stored in the address table.

Validation is done in the specific models. My problem is how can I ensure that the data is valid for both tables prior to saving them to database.

At the moment it is possible that the customer enters the correct data for the customer table which validates and gets saved to db but the address data does not validate and is not saved.

In short: I only want to save the data of any table to db if the data for all tables validates else I want to get the error messages.

Thanks for any help in advance.

tereško
  • 58,060
  • 25
  • 98
  • 150
user1036651
  • 407
  • 1
  • 5
  • 12

3 Answers3

0

First way is to use transactions, second - validate both address and customer data, and if both is valid - store.

  • 1. I have been thinking about transaction but since I use MyISAM and not InnoDB I am not able to use them. 2. Is there I way to call validation for a model without actually saving or updating. I haven't found it. – user1036651 Nov 09 '11 at 11:11
0

It's not clear from the documentation, but you can call the validate() method prior to calling save():

 public function test()
 {
     // Customers require an email address
     $cust = new Customer();
     $cust->first_name = "Me";
     $cust->validate();
     if ($cust->error->string)
     {
         echo $cust->error->string;
         // outputs The Email Address field is required.
     }
     else
     {
         // validation passed, save customer and related address to db
         $cust->save(array($address));
     }
 }
swatkins
  • 13,530
  • 4
  • 46
  • 78
0

If you have validation rules defined, you don't need to explicitly call validate(), the validation rules will also be checked when you call save().

In case validation failed, save() will return FALSE, after which you can check $this->valid to see if a validation error caused the save to fail.

WanWizard
  • 2,574
  • 15
  • 13