Gisto
Gisto

Reputation: 886

Joomla: How to pass variables from the constructor in the model to the view?

Seems like this shouldn't be that hard but is giving me fits.

Have variables initialized in the model's __construct method.

Need to access them in the view.html.php and default.php files.

In my model:

$this->MyVar = 'somevalue';

In my view.html.php:

$model = $this->getModel('mymodelname');
print_r($model) //checking, yes - the model's being pulled in
$myvar = $model->__construct($this->MyVar);
echo $myvar; //empty

What am I doing wrong and how do I fix it?

Thanks!

=========================================

Solution:

$model = $this->getModel('mymodelname');
echo $model->MyVar; // returns the variable in the model

Upvotes: 1

Views: 983

Answers (2)

Nir Alfasi
Nir Alfasi

Reputation: 53525

__construct() does not return any value, this is why $myvar remains null. If you want, you can read more about it here

According to the specification (in the link above) you should pass to __construct an associative array that could hold one or more of the following fields:

  • 'name'
  • 'state'
  • 'dbo'
  • 'table_path'

and according to what you say - you pass a parameter. Try:

$arr = array('name' => $this->MyVar);
$model->__construct($arr);

Upvotes: 2

Søren Beck Jensen
Søren Beck Jensen

Reputation: 1676

Why use construct at all after you have instantiated the model simply do like this:

$model = $this->getModel('mymodelname');
$model->MyVar = $myvar;

Upvotes: 1

Related Questions