Search code examples
phpblockadditioneditconcrete5

PHP Concrete 5 Pass Variables to Add.php


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:

// 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. Any suggestions? Thank you!

--- EDIT ---

From the concrete5 documentation:

// This...
$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

Solution

  • 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.

    Thanks for all the input. Hope that helps someone else!