PHP Concrete 5 Pass Variables to Add.php

霸气de小男生 提交于 2019-12-12 01:23:08

问题


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

回答1:


Calling $this->set('name', $value) in a block controller sets a variable of that name with the given value in the appropriate add/edit/view file -- you don't need to get it from within the controller object. So just call <?php echo $hasMap; ?> in your add.php file, instead of $myObj->hasMap.




回答2:


It will not be the same value, because the function will give diferrent values every timy it is called.




回答3:


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!



来源:https://stackoverflow.com/questions/12382362/php-concrete-5-pass-variables-to-add-php

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!