0

In my controller I am retrieving records from my institutions table with the following fields

 $params = array(
 'fields' => array(
 'Institution.id', 
 'Institution.name', 
 'Institution.about',              
 'Institution.picture'), 
 );

$institutions = $this->Institution->find('all',$params);

How can I prefix each 'Institution.picture' field with the full URL address, 'Institution.picture' itself only holds the name of the file.

I would also like to perform html_entity_decode() on each 'Institution.about' value from the returned set.

I know how to do this only without the framework if I make custom queries from scratch, then I would iterate each row and apply PHP functions to the field of interest. But is there a place in CakePHP (find or paginator) that I can specify such PHP manipulation on each field value from the returned set?

NOTE: I don't like to do this in the View, as I want to output it as json directly

Mike
  • 23,542
  • 14
  • 76
  • 87
Speed Demon
  • 691
  • 1
  • 9
  • 21

4 Answers4

3

You can define a virtualField for model:

public $virtualFields = array('image_url' => "CONCAT('/img/', Institution.picture)");

$params = array(
 'fields' => array(
 'Institution.id', 
 'Institution.name', 
 'Institution.about',              
 'Institution.picture',
 'Institution.image_url'), 
 );

$institutions = $this->Institution->find('all',$params);

Unfortunaly MySQL doesn't have a function to decode HTML entities. You may utilize an afterFind() callback instead of virtualField. This lets you to decode entities as well as add a prefix.

2

CakePHP is php

Just iterate over the array and prepare it however you want:

$institutions = $this->Institution->find('all',$params);

$prefix = '/img/'; // <- define this
foreach ($institutions as &$row) {
    $row['Institution']['about'] = html_entity_decode($row['Institution']['about']);
    $row['Institution']['picture'] = $prefix . $row['Institution']['picture'];
}

If this is always required it can be applied to all finds via an afterFind method in the institution class.

Community
  • 1
  • 1
AD7six
  • 63,116
  • 12
  • 91
  • 123
0

I think you should do it in the View. See this example.

tersmitten
  • 1,310
  • 1
  • 9
  • 23
0

Hash::map can be very useful here. By specifying path you can only modify slices of the set.

redd
  • 260
  • 2
  • 8