Passing variable to add.php from block controller

Permalink
I'm creating a new block and I want to pass a defined variable to the block instance on add.

In my controller, I have the following (among other stuff!):
// declare the var
public $hasMap = 0;
public function add() {
    $this->set('hasMap', $this->generateMapNumber());
}


The generateMapNumber() function looks like this:

public function generateMapNumber() {
    return intval(mt_rand(1,time()));
}


In my add.php form I have a hidden field:

<?php $myObj = $controller; ?>
<input type="hidden" name="hasMap" value="<?php echo $myObj->hasMap?>" />


When I create a new block, `hasMap` is always `0` and the hidden input value is always `0` too.

From the concrete5 documentation:

`$controller->set($key, $value)` takes a string $key and a mixed $value, and makes a variable of that name available from within a block's view, add or edit template. This is typically used within the add(), edit() or view() function.

Any suggestions? Thank you!

Jongosi
View Replies: View Best Answer
JohntheFish replied on at Permalink Reply
JohntheFish
Set variables are directly in the add/edit/view namespace:
Use:
echo $hasMap;
JohntheFish replied on at Permalink Reply
JohntheFish
Also you don't need to declare it at all in the controller. Doing that creates a totally different controller variable with the same name. So unless you want to play the mental gymnastics, its best not done.
Jongosi replied on at Permalink Reply
Jongosi
Thx John, if I call

echo $hasMap;


directly in add.php, it will have a value of 0. However, I need to assign the value to it from generateMapNumer() on add and retrieve the value of hasMap from the db on edit.

Does that make sense? :S Could I do this in add.php...

$myObj->generateMapNumber();


...and then modify the function to handle whether intval($this->hasMap)>0 in the controller?
Jongosi replied on at Permalink Best Answer Reply
Jongosi
So here's the solution. In the controller...

public $hasMap = 0;
// no need for this:
// public function add() {  }
public function generateMapNumber() {
    if (intval($this->hasMap)>0) {
        return $this->hasMap;
    } else {
        return intval(mt_rand(1,time()));
    }
}


And then in the add.php file...

<?php $myObj = $controller; ?>
<input type="hidden" name="hasMap" value="<?php echo $myObj->generateMapNumber()?>" />


It works perfectly. On add, a new number is generated and on edit, the existing number is drawn from the hasMap field in the db.

Hope that helps someone else!