在另一个视图中访问视图变量-Cakephp
我有一个名为View1.ctp的视图。在此视图中,我调用了一个名为“Captcha”的控制器函数,其视图为Captcha.ctp。我在view Captcha.ctp中有一个名为$text的变量。我想在View1.ctp中访问此$text变量。我该怎么办? (注:Cakephp版本-2.3)在另一个视图中访问视图变量-Cakephp,cakephp,Cakephp,我有一个名为View1.ctp的视图。在此视图中,我调用了一个名为“Captcha”的控制器函数,其视图为Captcha.ctp。我在view Captcha.ctp中有一个名为$text的变量。我想在View1.ctp中访问此$text变量。我该怎么办? (注:Cakephp版本-2.3) View1.ctp <h1>Add Comment</h1> <?php $post_id= $posts['Post']['id'];
View1.ctp
<h1>Add Comment</h1>
<?php
$post_id= $posts['Post']['id'];
echo $this->Form->create('Comment',array('action' => 'comment','url' => array($post_id,$flag)));
echo $this->Form->input('name');
echo $this->Form->input('email');
echo $this->Form->input('text', array('rows' => '3'));
echo "Enter Captcha Code: ";
echo $this->Html->image(
array('controller' => 'posts', 'action' => 'captcha'));
echo $this->Form->input('code');
echo $this->Form->end('Add comment');
?>
captcha.ctp:
<?php
$this->Session->read();
$text = rand(10000,99996);
$_SESSION["vercode"] = $text;
$height = 25;
$width = 65;
$image_p = imagecreate($width, $height);
$black = imagecolorallocate($image_p, 0, 0, 0);
$white = imagecolorallocate($image_p, 255, 255, 255);
$font_size = 14;
imagestring($image_p, $font_size, 5, 5, $text, $white);
imagejpeg($image_p, null, 80);
?>
添加注释
captcha.ctp:
更好的方法是将Captcha视图改为更合适的。因此,将captcha.ctp移动到app/View/Helper/captchaheloper.php,并将其内容包装在一个类中,如:
<?php
App::uses('AppHelper', 'View/Helper');
class CaptchaHelper extends AppHelper {
function create() {
// This line doesn't make much sense as no data from the session is used
// $this->Session->read();
$text = rand(10000, 99996);
// Don't use the $_SESSION superglobal in Cake apps
// $_SESSION["vercode"] = $text;
// Use SessionComponent::write instead
$session = new SessionComponent(new ComponentCollection());
$session->write('vercode', $text);
$height = 25;
$width = 65;
$image_p = imagecreate($width, $height);
$black = imagecolorallocate($image_p, 0, 0, 0);
$white = imagecolorallocate($image_p, 255, 255, 255);
$font_size = 14;
imagestring($image_p, $font_size, 5, 5, $text, $white);
// Return the generated image
return imagejpeg($image_p, null, 80);
}
}
(或者,如果已经有一个helpers数组,只需将其附加到该数组中即可。)
然后,从View1.ctp中,您只需调用帮助器即可返回图像:
echo $this->Html->image($this->Captcha->create());
它的“预期”值将存储在会话键
vercode
中,您也可以在表单处理逻辑中从PostsController读取该值。但是先生,我需要在另一个控制器CommentsController.php中访问此vercode,而不是在PostsController.ctpI中。我收到此错误先生。错误:调用成员函数read()在非-object@user1479469该错误来自$this->Session->read()
,这在Helper函数中没有任何意义,因此我将完全删除该行。要从另一个控制器读取会话密钥,只需从该控制器使用SessionComponent::read('vercode')
。oki sir..我改变了..我得到了这个错误-不应该静态调用非静态方法SessionComponent::write(),假设$this来自不兼容的上下文[APP\View\Helper\captchaheloper.php,第47行]确定,在这种情况下,将SessionComponent添加到控制器的$components
数组中:public$components=array('Session')然后使用$this->Session->read('vercode')代码>取而代之。
echo $this->Html->image($this->Captcha->create());