cakephp Ajax: city select box not populating when state is selected - ajax

I'm trying to populate the city select box based on the selected state (which is also a select box) using Ajax. When i select state, the city select box is not being populated.
There are 5 models below: Student, MerryParent, MerryClass, State, City. All of them are related to one another.
Can someone please tell me on what am I doing wrong? thank you.
The following are the models:
student.php
<?php
class Student extends appModel{
var $name='Student';
var $belongsTo=array('MerryParent','State','City','MerryClass');
}
?>
merry_parent.php
<?php
class MerryParent extends appModel{
var $name='MerryParent';
$hasMany=array(
'Student'=>array(
'className'=>'Student',
'foreignKey'=>'merry_parent_id'
)
);
$belongsTo=array('State','City','MerryClass');
?>
merry_class.php
<?php
class MerryClass extends AppModel{
var $name='MerryClass';
var $hasMany=array
('Student'=>array(
'className'=>'Student',
'foreignKey'=>'class_id'
),
'MerryParent'
);
var $belongsTo=array('State','City');
//var $displayField='class_name';
}
?>
city.php
<?php
class City extends AppModel{
var $name='City';
var $belongsTo='State';
var $hasMany=array('MerryParent','MerryClass',
'Student'=>array(
'className'=>'Student',
'foreignKey'=>'city_id'
)
);
}
?>
state.php
<?php
class State extends AppModel{
var $name='State';
var $hasMany=array(
'MerryParent',
'MerryClass',
'City'=>array(
'className'=>'City',
'foreignKey'=>'state_id'
//'dependent'=>true
),
'Student'=>array(
'className'=>'Student',
'foreignKey'=>'state_id'
)
);
}
?>
The controllers
students_controller.php
<?php
class StudentsController extends AppController{
var $name='Students';
var $helpers = array('Html','Form','Ajax','Javascript');
var $components=array('RequestHandler');
function getcities(){
$options=$this->Student->City->find('list',
array
('conditions'=>array(
'City.state_id'=>$this->data['Student']['state_id']
),
'group'=>array('City.name')
)
);//closing parentheses for find('list'...
$this->render('/students/ajax_dropdown');
}
function add(){
if (!empty($this->data)){
/*var_dump($this->data);
die(debug($this->Student->validationErrors)); */
$student=$this->Student->saveAll($this->data,array('validate'=>'first'));
if (!empty($student))
{
$this->Session->setFlash('Your child\'s admission has been received. We will send you an email shortly.');
$this->redirect(array('controller'=>'pages', 'action'=>'home'));
}
} //for if (!empty....
$states=$this->Student->State->find('list');
$cities=array();
$this->set(compact('states','cities'));
}//end function
}
?>
merry_parents_controller.php
<?php
class MerryParentsController extends AppController{
var $name='MerryParents';
}
?>
add.ctp
<?php
echo $javascript->link('prototype',false);
echo $form->create('Student');
echo '<fieldset>';
echo '<legend>Student Information</legend>';
echo $form->input('Student.name');
$options = array('Male'=>'Male','Female'=>'Female');
$attributes = array('value'=>'Male');
echo $form->radio('Student.gender',$options,$attributes);
echo $form->input('Student.dob', array('label'=>'Date of Birth',
'dateFormat'=>'DMY',
'empty'=>true,
'timeFormat' => '',
'minYear' => (
date('Y') - 5
),
'maxYear' => (
date('Y') - 2
)
));
echo $form->input('Student.class_id',
array(
'label'=>'Enquiry Class for',
'empty'=>'Choose one',
'options'=>array('1'=>'Playgroup','2'=>'Nursery','3'=>'LKG', '4'=>'UKG')
)
);
echo '</fieldset>';
echo '<fieldset>';
echo '<legend>Parent Information</legend>';
//echo $form->input('Student.parent_id', array('type'=>'hidden'));
echo $form->input('MerryParent.initial',
array('empty'=>true,
'options'=>array('Dr'=>'Dr',
'Mr'=>'Mr',
'Mrs'=>'Mrs',
'Ms'=>'Ms')
)
);
echo $form->input('MerryParent.name', array('label'=>'Parent/Guardian Name'));
echo $form->input('MerryParent.email');
echo $form->input('MerryParent.landline');
echo $form->input('MerryParent.mobile');
echo $form->input('MerryParent.address');
echo $form->input('Student.state_id');
echo $form->input('Student.city_id');
echo $form->input('MerryParent.postal_code');
$options = array('url' => 'getcities', 'update' => 'StudentCityId');
echo $ajax->observeField('StudentStateId', $options); //observes the drop down
changes in state id and makes an xmlHttpRequest when its contents have changed.
echo '</fieldset>';
echo $form->end('Submit');
?>
ajax_dropdown.ctp
<?php foreach($options AS $k=>$v) : ?>
<option value="<?php echo $k; ?>"><?php echo $v; ?></option>
<?php endforeach; ?>

You don't need to put 0 in Model name and field, since you are saving just one student in a form. Try using Student.name instead of Student.0.name and so on for all fields. Also try to test with $validate => false if it saves then.

Related

Fatch value in Dependent dropdown in Yii2

I created a Dependent drop-down now i want to fetch these values on update page. How can i do ?
I created 2 drop-down - 1st Client and 2nd Staff
on update page i got the value of client but i did not get the value of staff (Because it is dependent drop-down)
Form
<?php
//First drop-down
echo $form->field($model, 'client')->dropDownList($Client,
['prompt'=>'-Select Client-',
'onchange'=>'
$.post
(
"'.urldecode(
Yii::$app->urlManager->createUrl
('leads/lists&id=')).'"+$(this).val(), function( data )
{
$( "select#staff_id" ).html( data );
});
']); ?>
// depend dropdown
<?php echo $form->field($model, 'staff')
->dropDownList
(
['prompt'=>'-Choose a Sub Category-'],
['id'=>'staff_id','value'=>$Staff]
);
?>
Controller
public function actionLists($id)
{
$sql = "select * from staff where client='$id' ";
//exit;
$models = Staff::findBySql($sql)->asArray()->all();
//echo "<pre>";print_r($model);exit;
if(sizeof($models) >0){
echo "<option>-Choose a Sub Category-</option>";
foreach($models as $model){
echo "<option value='".$model['id']."'>".$model['fname']."</option>";
}
}
else{
echo "<option>-Choose a Sub Category-</option><option></option>";
}
}
first add $modelsStaff variable to your create and update actions like below:
<?
public function actionCreate()
{
$modelsStaff=null;
$model = new model();
if ($model->load(Yii::$app->request->post()) && $model->save())
{
return $this->redirect(['view', 'id' => $model->id]);
}
else
{
return $this->render('create', [ 'model' => $model,'modelsStaff'=>$modelsStaff]);
}
}
public function actionUpdate($id)
{
$model = $this->findModel($id);
if ($model->load(Yii::$app->request->post()) && $model->save())
{
return $this->redirect(['view', 'id' => $model->id]);
}
else
{
$sql = "select * from staff where client='$model->client'";
$modelsStaff = Staff::findBySql($sql)->asArray()->all();
return $this->render('update', [ 'model' => $model,'modelsStaff'=>$modelsStaff]);
}
}
?>
In your update action find all staff using $model->client and get all staff under this client and update your view like this
<?php
//First drop-down
echo $form->field($model, 'client')->dropDownList($Client,
['prompt'=>'-Select Client-',
'onchange'=>'
$.post
(
"'.urldecode(
Yii::$app->urlManager->createUrl
('leads/lists?id=')).'"+$(this).val(), function( data ) //<---
{
$( "select#staff_id" ).html( data );
});
']); ?>
// depend dropdown
<?php echo $form->field($model, 'staff')->dropDownList
($modelsStaff,
['prompt'=>'-Choose a Sub Category-'],
['id'=>'staff_id','value'=>$Staff]
);
?>
You have to create separate function in your controller (like an example):
public function actionLists($id)
{
$posts = \common\models\Post::find()
->where(['category_id' => $id])
->orderBy('id DESC')
->all();
if (!empty($posts)) {
$option = '<option>-Select Option-</option>';
foreach($posts as $post) {
$options .= "<option value='".$post->id."'>".$post->title."</option>";
}
return $options;
} else {
return "<option>-</option>";
}
}
and in view file (example):
use yii\helpers\ArrayHelper;
$dataCategory=ArrayHelper::map(\common\models\Category::find()->asArray()->all(), 'id', 'name');
echo $form->field($model, 'category_id')->dropDownList($dataCategory,
['prompt'=>'-Choose a Category-',
'onchange'=>'
$.post( "'.Yii::$app->urlManager->createUrl('post/lists?id=').'"+$(this).val(), function( data ) {
$( "select#title" ).html( data );
});
']);
$dataPost=ArrayHelper::map(\common\models\Post::find()->asArray()->all(), 'id', 'title');
echo $form->field($model, 'title')
->dropDownList(
$dataPost,
['id'=>'title']
);
This is from Yii docs: https://www.yiiframework.com/wiki/723/creating-a-dependent-dropdown-from-scratch-in-yii2

Yii chtml:listData from database with 1 key and 2 values

I have a dropdownlist populated with the database. It works just fine with 1 key and 1 value. But how would i get it to work with 1 key and 2 values. The 2 values are first name and last name.
<?php
$id = Yii::app()->user->id;
$clients = Clients::model()->findAll(array("condition"=>"cId = $id"));
$list = CHtml::listData($clients, 'id', 'fname');
?>
<?php echo $form->labelEx($model,'clientId'); ?>
<?php echo CHtml::dropDownList('clientId', $model, $list, array(
'empty' => 'Select a client',
'class' => 'form-control'
)); ?>
<?php echo $form->error($model,'clientId'); ?>
//needs something like this
$list = CHtml::listData($clients, 'id', 'fname lname');
I think you should define fullname as a virtual attribute and use it for your dropdownlist.
For example:
I suppose you have a model Person contain firstname and lastname. You can define a virtual attribute like:
class Person extends CActiveRecord {
public function getFullName()
{
return $this->firstname . " " . $this->lastname;
}
...
}
In a view, you can use CHtml::listData like:
echo $form->dropDownList($model, 'personid',
CHtml::listData( Person::model()->findAll(), 'id', 'fullname' )
);
I hope it's useful for you.
I used this easy way to con-cat attributes/strings in drop-down. You can even user third parameter for option group.
echo $form->dropDownListRow($model,'personid',
CHtml::listData(Person::model()->findAll(
array("select"=>"id,concat(firstname ,' ',lastname) as fullname")),
'id', 'fullname'));
in model Class
public $fullname;

Dependanat Drop down is not working when it has only one value in yii framework

I am using dependant dropdownlist for get value for subject dropdown when select value from 'Grade' dropdown. It is working fine. But the problem is when there are only one value in grade dropdown the subject dropdown is not updated.
this is my code:-
Grade DropDown----------
($data is consist of grade)
<?php echo CHtml::dropDownList('myDropDown1','',$data,array(
'id'=>'gr',
'empty' => '(Select Grade)',
'style'=>'width:200px',
'ajax' =>
array(
'type'=>'POST', //request type
'url'=>CController::createUrl('sub'), //action to call
'update'=>'#cls', // which HTML element to update
)
)); ?>
Subject Dropdown (which depend on grade dropdown)------------
<?php echo CHtml::label('Subject',''); ?>
<?php echo CHtml::dropDownList('myDropDown3','',array(),array(
'id'=>'sub',
'prompt'=> 'Please select a class', 'style'=>'width:150px',
'style'=>'width:200px',
)); ?>
<?php //echo $form->error($model,'sub_id'); ?>
In controller-------------------
public function actionClass()
{
$grd = $_POST['myDropDown1'];
$c_id = TbClass::model()->findAll('id=:id',
array(':id'=>$grd,));
$data3 = CHtml::listData($c_id,'id','grade');
$grd2 = array_shift($data3);
$sub1 = TbClass::model()->findAll('grade=:grade',
array(
':grade'=>$grd2,
));
$data4 = CHtml::listData($sub1,'id','class');
foreach($data4 as $value=>$name)
{
echo CHtml::tag('option',
array('value'=>$value),CHtml::encode($name),true);
}
}
This code is working fine. Problem is when grade has only one value in the dropdown , cannot update the subject dropdown.
I think your problem is in array_shift,
have you checked the value of $grd2 ?

Dynamic form in Yii

I'm having a problem creating something for my application. What i already have is a CJuiTabs system with a form in each tab. The number and values/names of the tabs is defined by a number of tinyInt columns in an another table in my database. The value of the tab is submitted with the form as a hidden field.
So now if you go to a view with an id you have already submitted a record with, you will be able to update that record, but you are not able to create new records with the other tab-values.
This is my problem. How do i make the application decide wether to create a new record or update an existing one based on which tab you have selected? If you are updating a record i would like to have the values of the record shown, but if you are creating a new one you should only see blank fields (well, its a rating system, so i guess it is stars not fields).
I guess it chould be done by using AJAX but i'm very much unsure of how to do that.
Game/view:
<?php
$tab_list=Platform::getPlatforms();
$tabarray=array();
// Create Dynamic Tabs
foreach($tab_list as $key=>$value){
$tabarray["$value"]=array(
'id'=>$key,
'content'=>$this->renderPartial('../ranking/_form',
array('model'=>$ranking, 'key'=>$key),TRUE)
);
}?>
<?php
$this->widget('zii.widgets.jui.CJuiTabs',array(
'tabs'=>$tabarray,
'options'=>array(
'collapsible'=>true,
),
'id'=>'categorytabs',
)); ?>
Models/Platform:
const PC = 1;
const Mac = 2;
const XBOX = 3;
const XBOX360 = 4;
const PS2 = 5;
const PS3 = 6;
const PSP = 7;
const PSVITA = 8;
const Wii = 9;
const WiiU = 10;
const NintendoDS = 11;
const NintendoDS3 = 12;
...
public function getPlatforms()
{
$id = Yii::app()->request->getQuery('id');
$platform = Platform::model()->findByPk($id);
$platforms = array();
if ($platform -> pc == 1)
{
$platforms[self::PC] = "PC";
}
if ($platform -> xbox == 1)
{
$platforms[self::XBOX] = 'XBOX';
}
if ($platform -> xbox360 == 1)
{
$platforms[self::XBOX360] = "XBOX 360";
}
if ($platform -> ps2 == 1)
{
$platforms[self::PS2] = "PS2";
}
if ($platform -> ps3 == 1)
{
$platforms[self::PS3] = 'PS3';
}
if ($platform -> psp == 1)
{
$platforms[self::PSP] = "PSP";
}
if ($platform -> psVita == 1)
{
$platforms[self::PSVITA] = 'PS VITA';
}
if ($platform -> wii == 1)
{
$platforms[self::Wii] = "Wii";
}
if ($platform -> wiiU == 1)
{
$platforms[self::WiiU] = "Wii U";
}
if ($platform -> nintendoDS == 1)
{
$platforms[self::NintendoDS] = 'Nintendo DS';
}
if ($platform -> nintendoDS3 == 1)
{
$platforms[self::NintendoDS3] = 'Nintendo DS3';
}
return $platforms;
}
Controllers/GameController:
public function actionView($id)
{
...
$ranking=$this->createRanking($model);
...
}
protected function createRanking($model)
{
$user_id=Yii::app()->user->getId();
$game_id=$model->id;
$rank=ranking::model()->find("create_user_id=$user_id and game_id=$game_id");
if($rank===null){
$ranking=new Ranking;
}
else{
$ranking=$rank;
}
if(isset($_POST['Ranking']))
{
$ranking->game_id=$model->id;
$ranking->attributes=$_POST['Ranking'];
$valid = $ranking->validate();
if ($valid)
{
$ranking->save(false);
$this->redirect(array('index'));
}
}
return $ranking;
}
Ranking/_form:
<?php $form=$this->beginWidget('CActiveForm', array(
'id'=>'ranking-form',
'enableAjaxValidation'=>false,
)); ?>
<p class="note">Fields with <span class="required">*</span> are required.</p>
<?php echo $form->errorSummary($model); ?>
<?php echo $form->hiddenField($model, 'platform_id', array('value' => $key)); ?>
<div class="row">
<?php echo $form->labelEx($model,'overall'); ?>
<?php $this->widget('CStarRating',array(
'model'=>$model,
'attribute' => 'overall',
)); ?>
<?php echo $form->error($model,'overall'); ?>
</div>
<br/>
<div class="row">
<?php echo $form->labelEx($model,'graphics'); ?>
<?php $this->widget('CStarRating',array(
'model'=>$model,
'attribute' => 'graphics',
)); ?>
<?php echo $form->error($model,'graphics'); ?>
</div>
<br/>
<div class="row">
<?php echo $form->labelEx($model,'sound'); ?>
<?php $this->widget('CStarRating',array(
'model'=>$model,
'attribute' => 'sound',
)); ?>
<?php echo $form->error($model,'sound'); ?>
</div>
<br/>
<div class="row">
<?php echo $form->labelEx($model,'gameplay'); ?>
<?php $this->widget('CStarRating',array(
'model'=>$model,
'attribute' => 'gameplay',
)); ?>
<?php echo $form->error($model,'gameplay'); ?>
</div>
<br/>
<div class="row">
<?php echo $form->labelEx($model,'lastingApp'); ?>
<?php $this->widget('CStarRating',array(
'model'=>$model,
'attribute' => 'lastingApp',
)); ?>
<?php echo $form->error($model,'gameplay'); ?>
</div>
<br/>
<div class="row buttons">
<?php echo CHtml::submitButton($model->isNewRecord ? 'Create' : 'Save'); ?>
</div>
<?php $this->endWidget(); ?>
I'm not sure I get this completely, let me try to see if I get the problem,
You have multiple forms one user can edit, they're all forms to rank one game on different gaming platforms (XBOX, PS2/3, etc..).
If this is the case, in your Game controller:
$rank=ranking::model()->find("create_user_id=$user_id and game_id=$game_id");
will always return the same db entry regardless of gaming platform (provided there is an entry)
You would need to use something along the lines of
$rank=ranking::model()->find("create_user_id=$user_id and game_id=$game_id and platform_id=$platform_id");
That covers the saving part but there's also an issue in the displaying. You have:
foreach($tab_list as $key=>$value){
$tabarray["$value"]=array(
'id'=>$key,
'content'=>$this->renderPartial('../ranking/_form',
array('model'=>$ranking, 'key'=>$key),TRUE)
);
In essence, you use the same $ranking model for each tab, so therefore the same (already existing) field inputs, or star ratings.
This is where it gets a little tricky. Ideally you would use Yii's relations To set up your models as Plateforms having multiple Games(MANY_MANY) that have multiple Ratings depending on Plateform/Game combination. Then you could do something along the lines of :
$platforms = Plateform::model()->findAll(array(
'with'=>array(
'rankings'=>array(
'condition'=>'game_id=$game_id AND platform_id=t.id')) //t refers to platform in Yii < 1.1.13. For Yii >= 1.1.13 check version update logs
));
foreach($platforms as $platform){
$tabarray[$platform->title]=array( //called it title arbitrarily, could be anything
'id'=>$platform->id,
'content'=>$this->renderPartial('../ranking/_form',
array('model'=>$platform->rankings[0], 'key'=>$platform->id),TRUE)
);
(I'm sparing you the use of 'params'=>array(), but do make it a habit.)
However you don't seem like you've gone that route, so check it out if you want, if not how about changing createRanking() to return an array of rankings corresponding to a platform for a given game using a key=> value where the key is the platform id. Then you could do:
foreach($tab_list as $key=>$value){
$tabarray["$value"]=array(
'id'=>$key,
'content'=>$this->renderPartial('../ranking/_form',
array('model'=>$rankings[$key], 'key'=>$key),TRUE)
);
If you went with that, as far as saving goes, if isset($_GET['Ranking']) then you would use the platform_id to isolate the correct model from the array in order to save it to db (or create a new one if it doesn't exist)
Hope that helps, or at least gets you on the right track.
edit: Added some code, not the best/cleanest solution but it should work and be easy to understand :
Controllers/GameController:
public function actionView($id)
{
...
$this->createRanking($model);
$rankings = $this->getRankingList();
...
}
//add this function
protected function getRankingList($gid,$uid)
{
$tab_list=Platform::getPlatforms();
$rankings = array();
foreach($tab_list as $key=>$value)
{
$rank=Ranking::model()->find("create_user_id=$user_id and game_id=$game_id and platform_id=$key");
if(empty($rank))
$rank = new Ranking;
$rankings[$key]= $rank;
}
return $rankings;
}
Game/view:
<?php
$tab_list=Platform::getPlatforms();
$tabarray=array();
// Create Dynamic Tabs
foreach($tab_list as $key=>$value){
$tabarray["$value"]=array(
'id'=>$key,
'content'=>$this->renderPartial('../ranking/_form',
array('model'=>$rankings[$key], 'key'=>$key),TRUE)
);
}?>
<?php
$this->widget('zii.widgets.jui.CJuiTabs',array(
'tabs'=>$tabarray,
'options'=>array(
'collapsible'=>true,
),
'id'=>'categorytabs',
)); ?>

Flash messanger in zf2

How can i use flash messenger in zend freamwork 2? Session documentation is not yet. Anyone know it? But session libraries are there.
Update :
Zend Framework new release added FlashMessenger View Helper , found in path /library/Zend/View/Helper/FlashMessenger.php
FlashMessenger.php
Old answer :
I have written a custom view helper, for printing flash messages
In /module/Application/Module.php
public function getViewHelperConfig()
{
return array(
'factories' => array(
'flashMessage' => function($sm) {
$flashmessenger = $sm->getServiceLocator()
->get('ControllerPluginManager')
->get('flashmessenger');
$message = new \My\View\Helper\FlashMessages( ) ;
$message->setFlashMessenger( $flashmessenger );
return $message ;
}
),
);
}
Create a custom view helper in /library/My/View/Helper/FlashMessages.php
namespace My\View\Helper;
use Zend\View\Helper\AbstractHelper;
class FlashMessages extends AbstractHelper
{
protected $flashMessenger;
public function setFlashMessenger( $flashMessenger )
{
$this->flashMessenger = $flashMessenger ;
}
public function __invoke( )
{
$namespaces = array(
'error' ,'success',
'info','warning'
);
// messages as string
$messageString = '';
foreach ( $namespaces as $ns ) {
$this->flashMessenger->setNamespace( $ns );
$messages = array_merge(
$this->flashMessenger->getMessages(),
$this->flashMessenger->getCurrentMessages()
);
if ( ! $messages ) continue;
$messageString .= "<div class='$ns'>"
. implode( '<br />', $messages )
.'</div>';
}
return $messageString ;
}
}
then simple call from layout.phtml , or your view.phtml
echo $this->flashMessage();
Let me show example of controller action
public function testFlashAction()
{
//set flash message
$this->flashMessenger()->setNamespace('warning')
->addMessage('Mail sending failed!');
//set flash message
$this->flashMessenger()->setNamespace('success')
->addMessage('Data added successfully');
// redirect to home page
return $this->redirect()->toUrl('/');
}
In home page, it prints
<div class="success">Data added successfully</div>
<div class="warning">Mail sending failed!</div>
Hope this will helps !
i have written a post about this some time ago. You can find it right here
Basically you use it just the same like earlier.
<?php
public function commentAction()
{
// ... display Form
// ... validate the Form
if ($form->isValid()) {
// try-catch passing data to database
$this->flashMessenger()->addMessage('Thank you for your comment!');
return $this->redirect()->toRoute('blog-details'); //id, blabla
}
}
public function detailsAction()
{
// Grab the Blog with given ID
// Grab all Comments for this blog
// Assign the view Variables
return array(
'blog' => $blog,
'comments' => $comments,
'flashMessages' => $this->flashMessenger()->getMessages()
);
}
Then in your .phtml file you do it like this:
// details.phtml
<?php if(count($flashMessages)) : ?>
<ul>
<?php foreach ($flashMessages as $msg) : ?>
<li><?php echo $msg; ?></li>
<?php endforeach; ?>
</ul>
<?php endif; ?>
Obviously this isn't all too handy, as you have to do this for every single .phtml file. Therefore doing it within the layout you have to do it at best like the following:
<?php
// layout.phtml
// First get the viewmodel and all its children (ie the actions viewmodel)
$children = $this->viewModel()
->getCurrent()
->getChildren();
$ourView = $children[0];
if (isset($ourView->flashMessages) && count($ourView->flashMessages)) : ?>
<ul class="flashMessages">
<?php foreach ($ourView->flashMessages as $fMessage) : ?>
<li><?php echo $fMessage; ?></li>
<?php endforeach; ?>
</ul>
<?php endif; ?>
If you need further description, please see my blog, but i guess the code itself is pretty clear (apart frmo the layout.phtml example). Alternatively you're always free to write your own view helper to have it look a little cleaner inside your view-templates.
How to grab Flashmessenger’s messages in a View Helper – sharing code as requested by Sam.
The View helper should implement the ServiceManagerAwareInterface interface and related methods. The plugin will now have access to a Service Manager which we can use to get the Service Locator and ultimately access to the Flash Messenger.
I’ve not touched this code since I initially wrote it – so there may be a more elegant way of doing this.
protected function getMessages()
{
$serviceLocator = $this->getServiceManager()->getServiceLocator();
$plugin = $serviceLocator->get('ControllerPluginManager');
$flashMessenger = $plugin->get('flashmessenger');
$messages = $flashMessenger->getMessages();
// Check for any recently added messages
if ($flashMessenger->hasCurrentMessages())
{
$messages += $flashMessenger->getCurrentMessages();
$flashMessenger->clearCurrentMessages();
}
return $messages;
}
And calling getMessages() from within the plugin should return an array of messages that can be passed to a partial and rendered.
Add code below to the view to render error messages:
<?php echo $this->flashmessenger()
->setMessageOpenFormat('<div class="alert alert-danger"><ul%s><li>')
->setMessageCloseString('</li></ul></div>')
->render('error')
; ?>
In previous request, make sure you created an error message by running code below in your controller:
$this->flashmessenger()->addErrorMessage('Whops, something went wrong...');

Resources