Last Updated: February 25, 2016
·
1.087K
· my3recipes

CakePHP 3.0 - Use Collection to format tags as string divided by commas

CakePHP 3.0 has a great library Collections :

The collection classes provide a set of tools to manipulate arrays or Traversable objects. If you have ever used underscore.js you have an idea of what you can expect from the collection classes.

Collection instances are immutable, modifying a collection will instead generate a new collection. This makes working with collection objects more predictable as operations are side-effect free.

You can use it to work with search results. Let's take an example - we want to edit Note tags. We will put tags as a string, separated by commas.

// App/Controller/NotesController.php
...

$data = $this->Notes->get($id, [
  'contain' => ['Tags']
]);

$this->set('tag_list', implode(", ", 
  (new Collection($data->tags))->extract('name')->toArray()));

You see, we're creating a new Collection from Note tags, then extract field name and converting results into Array. Which will be imploded by commas. All this in only one single line.

We have a string, so let's just put it into form input:


// App/Template/Notes/edit.ctp
...

<?= $this->Form->input('tag_list', ['value' => $tag_list]);?>