Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

cakephp behavior afterFind not called on related models

I am using an afterFind function to modify data from a find function. It works fine. If I move the afterFind function into a behavior (in a plugin) it still works, but only when the model of interest is the primary model, i.e. it isn't called when the model belongsTo another model. Is there any way round this? I'm using cake 1.3.4. This is a simplified version of the behavior:

class ChemicalStructureBehavior extends ModelBehavior {
    function afterFind(&$model, $results, $primary) {
        foreach ($results as &$unit) {
            // format chemical formula (with subscripts)
            $unit[$model->alias]['chemical_formula_formatted'] = preg_replace('/([0-9]+)/i', '<sub>$1</sub>', $unit[$model->alias]['chemical_formula']);
        }

        return $results;
    }
}
like image 308
Tomba Avatar asked Oct 26 '10 22:10

Tomba


2 Answers

I guess I'd do one of 2 things depending on how generically the code block applies:

  1. Universal version: not use a behavior, but include your method block in AppModel::afterFind
  2. Surgical version: use a behavior and attach it to each model that needs to share the functionality.
like image 167
Rob Wilkerson Avatar answered Sep 21 '22 02:09

Rob Wilkerson


A behavior isn't supposed to work on related models, for example, if you have this two models:

app/models/product.php

<?php

class Product extends AppModel{
    var $belongsTo = array('Category');
    var $actsAs = array('SomeBehavior');
}

?>

app/models/category.php

<?php 

class Category extends AppModel {
    var $hasMany = array('Product');
}

?>

SomeBehavior will only be executed when calling methods for Product, because the behavior isn't associated with Category

like image 40
Mauro Zadunaisky Avatar answered Sep 22 '22 02:09

Mauro Zadunaisky