Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

CakePHP asking for model table despite useTable = false

Tags:

cakephp

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?

like image 935
Adam Avatar asked Sep 26 '09 19:09

Adam


5 Answers

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.

like image 56
deizel Avatar answered Nov 07 '22 14:11

deizel


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.

like image 30
Michael Avatar answered Nov 07 '22 15:11

Michael


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');

?>
like image 28
deewilcox Avatar answered Nov 07 '22 13:11

deewilcox


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.

like image 2
Rob Wilkerson Avatar answered Nov 07 '22 14:11

Rob Wilkerson


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')
    );
}
like image 2
Mathew Attlee Avatar answered Nov 07 '22 13:11

Mathew Attlee