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:
Modyfying request data before building entities
HasMany Association
Virtual Properties