Skip to content

Instantly share code, notes, and snippets.

@Caffe1neAdd1ct
Last active November 23, 2016 20:05
Show Gist options
  • Save Caffe1neAdd1ct/b6f4439c32ccd0c93347d36a51b57021 to your computer and use it in GitHub Desktop.
Save Caffe1neAdd1ct/b6f4439c32ccd0c93347d36a51b57021 to your computer and use it in GitHub Desktop.
Phalcon flash messages with Bootstrap 3 integration
<?php
namespace Ext;
/**
* Extension to Phalcon Framework to implement Bootstrap 3 dismissable messages.
* Pass mappings of phalcon to bootstrap classes to construct
* @link https://docs.phalconphp.com/uk/latest/reference/flash.html Phalcon flash docs
* @author Kevin Andrews <[email protected]>
*/
class FlashBootstrap extends \Phalcon\Flash\Session
{
protected $_cssClasses = [
'error' => 'alert alert-danger alert-dismissible',
'notice' => 'alert alert-info alert-dismissible',
'success' => 'alert alert-success alert-dismissible',
'warning' => 'alert alert-dismissible'
];
/**
* Correctly escapes the message while building a Bootstrap 3
* compatible dismissable message with surrounding html.
* @param string $type
* @param string $message
* @return void
*/
public function message($type, $message)
{
$bootstrapCssClass = $this->_cssClasses[$type];
$errorType = ucfirst($type);
$bootstrapMessage = "<div class=\"{$bootstrapCssClass}\" role=\"alert\"><button type=\"button\" class=\"close\" data-dismiss=\"alert\" aria-label=\"Close\"><span aria-hidden=\"true\">&times;</span></button><strong>{$errorType}:</strong> {$this->getEscaperService()->escapeHtml($message)}</div>";
parent::message($type, $bootstrapMessage);
}
}
@Caffe1neAdd1ct
Copy link
Author

Initialise in services like so:

$di->set('flash', function() {
    $bootstrapFlash = new Ext\FlashBootstrap(array(
        'error' => 'alert alert-danger alert-dismissible',
        'success' => 'alert alert-success alert-dismissible',
        'notice' => 'alert alert-info alert-dismissible',
        'warning' => 'alert alert-dismissible',
    ));
    $bootstrapFlash->setAutoescape(false);
    $bootstrapFlash->setAutomaticHtml(false);
    return $bootstrapFlash;
});

@Caffe1neAdd1ct
Copy link
Author

Caffe1neAdd1ct commented Nov 21, 2016

Html is built up inside message which is used by all helper methods (->success(),'error->()',notice-.(),warning->())
The message is escaped using $this->getEscaperService()->escapeHtml($message) and disabled in the parent class to allow custom Bootstrap html.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment