Saving data in CakePHP
CakePHP February 20th, 2007To save in your model using CakePHP you only have to supply that data to a specific model using the save() method.
The data needs to be in the following form:
To post data in this form to a controller for example is very easy using HTML helpers that are implemented in Cake. Everything we need to care about is that form elements are looking like: data[Modelname][fieldname] .
For example to acces a certain variable in a controller we will use;
-
$name_var = $this->data[‘Modelname’][‘formvariable’];
The input form in the view will look something like this:
-
$html->input('Modelname/formvariable')
In a form construction using helpers is best to respect the model structure using to give names to form elements the same names like fields we want to fill in the database.
Using this convention data sent from forms will be formatted automatically and will look putted in $this->data within you controller, so saving data becomes very easy.
Example of saving data:
-
function add() // action add
-
{
-
{
-
if ($this->Car->save($this->data)) // is data is saved returns true
-
{
-
$this->flash('Your post has been saved.','/posts'); //displaying message with link
-
}
-
}
-
}
In the example above we are saving data in the Car model.
If you want to validate your data you can easily do this using your model.
Example:
-
class Car extends AppModel
-
{
-
var $name = Car';
-
var $validate = array(
-
'name' => VALID_NOT_EMPTY,
-
'model' => VALID_NOT_EMPTY
-
'year' => VALID_NOT_EMPTY
-
);
-
}
Cake will check variables: name, model and year not to be empty.
In on of the next posts I will describe how easy is to save data in multiple related models.
February 4th, 2008 at 6:22 pm
I have a problem here
I have 2 table that has not associated each other, and 1 form, when submit
table1 do to save the data from that form, and table2 save the data with my own variable which is not from the form.
my question is how I save some data to table2?
that cakePHP have a special command or some trick?
or we just use command mysql_query(”$insert_sql”)
like the common insert SQL?
February 6th, 2008 at 3:42 am
From what you describe me I think you can use save() method twice to save the data in those 2 different tables.