Create custom functions and pass arguments from view

So let’s just say that i want to calculate the average age of my users so i create a function wich recieves an array and return the average.
how can i pass arguments to this function? is it possible?

Are you asking how to do this in CakePHP specifically, or in PHP in general?

Hi, im asking in cakephp

The Cake way to do this would probably be with a collection.

This assumes that you have the data all loaded, based on your comment about “receives an array”. It’s almost certain, however, that you’d be better off doing this with a database query that doesn’t need to load all that data into PHP. The query builder includes a function for averaging.

Yeah i know. It was just an example but there are cases that its not possible to do it with a query. Like have a status bar wich changed the color based on, say, the grade of a student. I want to do something like $student->status($student->grade)
And this function returns a string or something. Is this posible in cake?
I think that Cells is the closer aproach but needs to render… Otherwise i will try with some Js

Is it possible to call functions, which you pass parameters to, in CakePHP? Obviously so. It’s still PHP. So it seems like maybe you’re not expressing your real question well.

To your example, assuming that $student is an instance of the Student entity class, you could indeed write a function in Student called status, which takes a Student entity as a parameter. But why? In the theoretical status function, you can already reference the student entity in question via $this. You could even go one better by writing an accessor in the Student class, like:

protected function _getStatus() {
    return ($this->grade > 80 ? 'green' : 'red');
}

and it would be called very simply like $student->status.

If the thing you’re returning is more complicated, e.g. one of a group of icons from your webroot, then an element is maybe the way to go.

Now, if you had a Student entity without any marks associated with it, and you wanted to read all their marks and generate some bit of output based on that, then that’s where you need a cell.

Really not seeing where any kind of JS solution would be useful.

You can create a helper in cakephp to get the solution for your query