开发者

CakePHP: HTML in setFlash()

I'm wondering if there is any proper way to include HTML in the setFlash() function of the Session component.

Basically I have this admin interface on an e-commerce website which allows administrators to create and edit "shops" found on the website. Upon saving the "shop", I would like CakePHP to display something like "Your shop has been successfully saved. Return to Shop Index". "Return to Shop Index" would be a link. I'm currently using plain old HTML like:

$this->Session->setFlash("Shop has been successfully published. <a href=\"...\">Return to Shop Index</a>");

Works, but it's HTML in the Controller, which I think is a "bad thing".

Thanks!

EDIT:

Thanks @YonoRan for solution. Missed that out in the CakePHP documentation. Here's what I did:

1) Created new element session_flash_link.ctp in app/views/elements.

2) Added the following code in ses开发者_运维知识库sion_flash_link.ctp:

<div id="flashMessage" class="message">
<?php
echo $message;
echo $this->Html->link($link_text, $link_url, array("escape" => false));
?>
</div>

3) Code in controller:

$this->Session->setFlash("Shop has been successfully saved. ", "session_flash_link", array(
    "link_text" => "Return to Shop Management &raquo;",
    "link_url" => array(
        "controller" => "shops",
        "action" => "manage",
        "admin" => true
    )
));


This might be a solution for what you are trying to do, it loads a "Layout" with all the HTML in it as a setFlash message. Custom CakePHP flash message

Update:

I just checked the Manual for setFlash SetFlash Manual

And it shows that you can specify and element that holds the HTML for the setFlash message + a bunch of other properties.

setFlash($message, $element = 'default', $params = array(), $key = 'flash')

So it seems like a better way of doing whats suggested in the first link I posted, because it doesn't require a new layout but just uses Elements.

Good luck.


I've just found another way to do this that doesn't need new specific templates:

You can use the HtmlHelper - which you can access since it's probably loaded in the view, and we have access to that:

// access the html helper
$Html = (new View($this))->loadHelper('Html');
// use it to generate a link    
$resend = $Html->link(__('resend'), array(
    'controller' => 'users',
    'action' => 'resend',
));
// sprintf to insert the link to your standard message text!
$this->Session->setFlash(sprintf(_("Do you want to %s the email?"), $resend));

Should work in any case where you need Helper functionality in a View. Works in 2.3.5.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜