Question

I'm currently using CakePHP 2.x.

I make all my forms using the form_helper and then the active record way to save the model data. It's really tidy and simple, but I can't find the way to save one particular structure.

I've 2 tables, one for the user basic information and one for the user details, with a lot of different fields: User and User_Detail.

User:

id | name | email
------------------------
1  | John | john@doe.com
2  | Paul | paul@doe.com

User_Detail:
id | user_id | field  | value
-----------------------------
1  | 1       | sex    | m
2  | 1       | age    | 21
3  | 2       | height | 180

What's the best way to make the user fill some fields? What fields to complete can be hardcoded in the app. Is it possible using a form helper and saveRelationship()?

Was it helpful?

Solution

Based on your comments, I would add a new table that contains the name of the "custom fields", lets call it "custom_fields" and this would be its definition

custom_fields: id name

Its model is called CustomField and it hasMany UserDetail

Your user_details table will have this structure

user_details: id user_id custom_field_id value

This model (UserDetail) belongsTo CustomField.

Your model User hasMany UserDetail.

Now, in your users form you might want to have a select with all possible CustomValues, in order to do this you previously did something like this in your controller

$customValues = $this->CustomValues->find('list');
$this->set(compact('customValues'));

So, in your view you will have something like this

echo $this->Form->input('UserDetail.custom_field_id', array('type' => 'select', 'values' => $customValues));
echo $this->Form->input('UserDetail.value')

And of course, after submitting this form you will call Model::SaveAssociated

I hope you have now the idea.

OTHER TIPS

Assuming that I understand what your trying to do ..... If using Form Helper you can construct your input fields as follows:

echo $this->Form->input('User.name');
echo $this->Form->input('User.email');
echo $this->Form->input('User_Detail.sex');
echo $this->Form->input('User_Detail.age');
echo $this->Form->input('User_Detail.height');

Then when you save you should use saveAssociated($this->request-data) and it should work by saving the record into both models and automatically creating the appropriate User_Detail.user_id field.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top