I'm using CakePHP to learn about it. I've made a CRUD with relationship, products/categories
, in the products form i want to put a field named tags
, separated by comma and insert in another table each tag separated. Examples.
Form products (input:tag)
one,two,four
tags (table)
id | product_id | tag
1 2 one
2 2 two
I have no ideia how to do it.
What you need to do here is to modify your data before modyfying your entity. Luckily, there is Model.beforeMarshal
event, which allows you to do exactly this. A quick and untested example below:
//put this in your Table class
public function beforeMarshal(Event $event, ArrayObject $data, ArrayObject $options){
if(!empty($data["tag_string"]){
$tags = explode(", ",$data["tag_string"]);
$tagsData = [];
foreach($tags as $tag){
$tagsData[] = ["tag" => $tag];
}
$data["tags"] = $tagsData;
}
}
Please note, that I changed tags
to tag_string
- it's because tags
, if you followed CakePHP conventions, will be reserved for your association. Also, by default, your tags will be appended to existing ones, so you need to change your saving strategy with "saveStrategy" => "replace"
in your association definition.
You need also to retrieve your tag string - to do this, you need to create virtual property in your entity:
//put this in your Entity
protected function _getTagString(){
$tagString = "";
for($i = 0; $i < count($this->tags); $i++){
$tagString .= $this->tags[$i]->tag;
if($i != count($this->tags) - 1){
$tagString .= ", ";
}
}
return $tagString;
}
With this, you can then retrieve your tag string by calling $product->tag_string
.
More info can be found in CakePHP cookbook: