I'm creating a contact form to send an email to a specified address. I'm trying to utilize CakePHP model validations and since I don't need a table for the contact model, I've set useTable to false in the contact model. Yet I'm getting an error in the controller function that does the sending. The error is
Missing Database Table Error: Database table contacts for model Contact was not found.
pointing to the line that makes the first call to $this->Contact:
$this->Contact->validates( $this->data );
I thought this was all good to go with the CakePHP framework. Why am I wrong?
Edit: See this answer (and comment) for CakePHP 2.x (model file should be called Contact.php
)
CakePHP 1.x - Verify that your model file is called contact.php
(lowercase). If it is not, CakePHP won't find your model and and will instead create an "autoModel" on runtime called Contact
which uses the contacts
table.
This is a top result to a search but the information is outdated I think.
In CakePHP 2.0+ you need to set $useTable = false;
in the model, the model name uses propercase (so it should be Contact
and not contact
as suggested) and the controller must have $uses = 'Contact';
or $uses = array('Contact');
or cake generates default model properties and tries to load a table that doesn't exist. So both of these things must be set for it to work.
Two things made the difference for me -- changing the file name of my model to Contact.php (instead of ContactModel.php) and commenting out var $uses = 'Contact';
in my ContactController.php.
Also, many of the tutorials out there for contact forms are for earlier versions of CakePHP. Be sure to use the correct form input structure. Here is the view for mine in Cake 2.1:
<?php
echo $this->Form->create('Contact');
echo $this->Form->inputs();
echo $this->Form->end('Send');
?>
If memory serves, you're not actually setting your model:
$this->Contact->set( $this->data );
$this->Contact->validates();
In your code, the model isn't actually populated when you try to validate it.
If you are using a model without a table you also need to set a schema eg
class Contact extends AppModel {
var $name = 'Contact';
var $useTable = false;
var $_schema = array(
'name' => array('type' => 'string', 'length' => 255),
'email' => array('type' => 'string', 'length' => 255),
'message' => array('type' => 'text')
);
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With