I have a form that has all the fields pulled dynamic from a database table 'FieldNames':
ID | FieldName
--------------
11 | username
22 | password
33 | Address
44 | etc
This is just an example, the form is more complex.
I have learned and saw in php doc that if the form fields match 1:1 with the model table the Save method is user and a new row gets created with all the values in the proper cells. But how does it work if for my sample form all fields values should get in multiple lines, one by one in a table 'FieldValues' with the following structure.
ID | FieldId | Value | DataSet
---------------------------------------------
1 | 11 | 'value for username' | 1
2 | 22 | 'value for password' | 1
3 | 33 | 'value for address' | 1
FieldId = FK to Fieldnames.ID
I was able to do this in a method using the "classic"
foreach field -> $sql = "sql insert query" -> $this->query( $sql )'
I was just wondering is i can use the "magic" in cake to solve this task. Second question: If the "magic" is possible, how can i add a second parameter and on each data set to set a new DataSet value ?
This is a form builder app so the fields HAVE to be dynamic and I cannot use the "static" form implementation (hardcode the fields names in table columns 1:1). The field names and number vary. That's why I'm pulling them for the database.
I suggest you to create a method in your model (where you want to save your fields) like:
// Field model
public function saveFields($data) {
foreach($data as $field) {
$this->save($field);
}
}
You can call this function in your FieldsController Add Action:
// FieldsController
$this->Field->saveFields($this->request->data);
Or in any other Controller / Model by using ClassRegistry:
// FooController
$Field = ClassRegistry::init('Field');
$Field->saveFields($this->request->data);
Be sure that your data is in the proper format like:
$data [0] [ ModelName ] = array(
Field1 => Value1,
Field2 => Value2
)