I have a session class as follows:
<?php
class Session {
function __construct() {
if (empty(session_id())) {
session_start();
}
}
function AddMessage($msg="") {
if (!is_array($_SESSION['messages'])) {
$_SESSION['messages'] = [];
}
array_push($_SESSION['messages'], $msg);
}
function GetMessages() {
$messages = $_SESSION['messages'];
unset($_SESSION['messages']);
return $messages;
}
}
?>
Also there is a php file in my layouts directory:
<?php if (!empty($_SESSION['messages'])) { ?>
<div class="messages">
<ul>
<?php
$messages = $session->GetMessages();
foreach ($messages as $message) {
echo "<li class=\"message\">{$message}</li>";
}
?>
</ul>
</div>
<?php }?>
This piece of code above is included at the top of my pages.
The problem is that in case of single-page submission handling -done in the middle of the page - the messages are printed out before I set it with the AddMessage() method.
Is there a simple way to get around this issue, or I have to rethink my code flow?
Related
I am trying to set up platesphp for one of my projects.
One of the methods in the model checks for the email address supplied by a new user and tells if the email they trying to use exists or not.
Something like
class UserModel extends BaseModel
{
public $errors = [];
public function validate()
{
if (filter_var($this->request->post['email'], FILTER_VALIDATE_EMAIL) === false) {
$this->errors[] = 'Invalid email';
}
if ($this->emailExists($this->request->post['email'])) {
$this->errors[] = 'Email already exist';
}
}
protected function emailExists($email)
{
$sql = 'SELECT * FROM user_account WHERE email = :email';
-----
-----
$stmt->execute();
return $stmt->fetch() !== false;
}
}
and in the controller
public function register()
{
$this->load->getModel('UserModel');
if ($this->model_UserModel->registerUser($this->request->post)) {
echo "Success ... load (redirect) second page";
} else {
$data ['error'] = $this->model_UserModel->errors;
echo $this->template->render('home/home', $data);
}
}
If the email exists and I var dump $data ['error'] it says "Email already Exist" as defined in the validate method in the UserModel.
Now, I am trying to get the error message on my home template by adding these lines on the tpl file
<?php if (!empty($this->e($errors))): ?>
<?php foreach($errors as $error): ?>
<li><?=$this->e($error)?></li>
<?php endforeach ?>
<?php endif;?>
But now if I click on the register page the template says
Notice: Undefined variable: errors in C:\xampp\htdocs\vem\App\Views\template\register\registeruser.tpl on line 14
How do I move forward?
I even tried setting the $this->e($error) = '' but naa, shows another error.
On your controller, you're setting variable error, but in template, you're accessing variable errors (with s).
Try with
<?php if (#$error)): ?>
<?php foreach($error as $e): ?>
<li><?=$this->e($e)?></li>
<?php endforeach ?>
<?php endif;?>
You need use error not errors:
<?php if (!empty($this->e($error))): ?>
<?php foreach($error as $error_item): ?>
<li><?=$this->e($error_item)?></li>
<?php endforeach ?>
<?php endif;?>
I have a small issue i have declared a variable of type Boolean in my controller.
$done=False
Now there is a trigger in the controller that would turn it to True and it is at this point i would like to send it to the corresponding view with this controller .. i have used the following.
$done=True;
$this->view->setVar("done", $done);
Now when i try to call it in the corresponding view it does not know anything of this varible.
if($done==True)
{
echo'
<div class="alert alert-success">
Add Another Here!
</div>
';
}
It gives me the following:
Notice: Undefined variable: done in >C:\xampp\htdocs\Blueware\app\views\addNewSkill\index.phtml on line 36
Now is there a better way of sending this varible through to the view or am i making a mistake?
Full Controller/Action Code:
<?php
class addNewSkillController extends \Phalcon\Mvc\Controller{
public function indexAction(){
}
public function confirmAction(){
$this->view->disable();
$done=False;
if($this->request->isPost()) {
$dataSent = $this->request->getPost();
$skill = new Skills();
$skill->technology = $dataSent["technology"];
$skill->skillName = $dataSent["skillName"];
$skill->description = $dataSent["description"];
$savedSuccessfully = $skill->save();
if($savedSuccessfully) {
$done=True;
$this->view->setVar("done", $done);
} else {
$messages = $skill->getMessages();
echo "Sorry, the following problems were generated: ";
foreach ($messages as $message) {
echo "$message <br/>";
}
}
} else {
echo "The request method should be POST!";
}
}
}
Full View Code:
<?php
if($done==True)
{
echo'
<div class="alert alert-success">
Add Another Here!
</div>
';
}
?>
if($savedSuccessfully) {
$done=True;
$this->view->setVar("done", $done);
} else {
You should be setting the variable there, But setting in the view after seems that its not saving and therefore not passing the variable on
similar to
if($savedSuccessfully) {
$done=True;
} else {
...later in code ...
$this->view->setVar("done", $done);
or even just
$this->view->setVar("done", $savedSuccessfully);
I have a form and the submit button check if true or false.
If it's true redirect to another page.
If it's false stay on the same page and print the error message.
The error message is print out with a flash messenger.
But, in some case it doesn't print in the first try when submit is false, it always print out on the second click.
Did I did something wrong?
And also, is there a way to set difference flash messenger name? Because, on my others pages that have flash messenger, print out the error when page is refreshed.
Here's the code:
if(isset($_POST['submit'])) {
// code to inputfields
if(true) {
//redirect to some page
} else {
// print the flash error on the same page
$this->_helper->flashMessenger->addMessage(" This email is already taken");
$this->view->messages = $this->_helper->flashMessenger->getMessages();
}
}
HTML:
<center>
<div style="color:red">
<?php if (count($this->messages)) : ?>
<?php foreach ($this->messages as $message) : ?>
<div id="field_name">
<strong style="text-transform:capitalize;">Email </strong>
- <?php echo $this->escape($message); ?>
</div>
<?php endforeach; ?>
<?php endif; ?>
</div>
</center>
flashmessenger is really designed to be used on a redirect of some kind, so any message you see probably comes from the prior action's execution. Your current code would not flash any message during the first 'post'.
you may have some luck if you try something like:
public function init()
{
//This will catch any messege set in any action in this controller and send
//it to the view on the next request.
if ($this->_helper->FlashMessenger->hasMessages()) {
$this->view->messages = $this->_helper->FlashMessenger->getMessages();
}
}
public function someAction()
{
if(isset($_POST['submit'])) {
// code to inputfields
if(true) {
//redirect to some page
} else {
// print the flash error on the same page
$this->_helper->flashMessenger->addMessage(" This email is already taken");
//will redirect back to original url. May help, may not
$this->_redirect($this->getRequest()->getRequestUri());
}
}
}
Here's an action I coded that demonstrates what you seem to be attempting.
public function updatetrackAction()
{
//get the page number
$session = new Zend_Session_Namespace('page');
$id = $this->getRequest()->getParam('id');
//get the entity object
$model = new Music_Model_Mapper_Track();
$track = $model->findById($id);
//get the form
$form = new Admin_Form_Track();
$form->setAction('/admin/music/updatetrack/');
//test for 'post' 'valid' and update info
if ($this->getRequest()->isPost()) {
if ($form->isValid($this->getRequest()->getPost())) {
$data = $form->getValues();
$newTrack = new Music_Model_Track($data);
$update = $model->saveTrack($newTrack);
//add message
$this->message->addMessage("Update of track '$update->title' complete!");
//redirects back to the same page number the request came from
$this->getHelper('Redirector')->gotoSimple('update', null, null, array('page' => $session->page));
}
} else {
//if not post display current information
//populate() only accepts an array - no objects -
$form->populate($track->toArray());
$this->view->form = $form;
}
}
Please check this below code. After for loop remaining code is not executing. It suppose to print "Helo", but it is not printing any thing.
for($i=0;$i<10;$i++)
{
$minrate=$obj_iScripts->min_avg_rate($roomnumber[$id_array[$i]], $amount_ary[$id_array[$i]], $totalrooms);
$all_min_price[]=$minrate;
if($_SESSION['star'][$id_array[$i]]>=1 && $_SESSION['star'][$id_array[$i]]<=5)
{
//include 'searchresult_table.php';
}
}
echo "Helo";
code:
public function min_avg_rate($roomnumber,$rates,$totalrooms)
{
$ary_name='iArray';
$total=0;
for($i=1;$i<=$totalrooms;$i++)
{
${$ary_name.$i}=array();
$temp=max($rates);
for($j=0;$j<count($roomnumber);$j++)
{
if($roomnumber[$j]==$i)
{
if($temp>$rates[$j])
$temp=$rates[$j];
${$ary_name.$i}=$temp;
}
}
$total=$total+${$ary_name.$i};
}
return $total/$totalrooms;
}
From what code you have posted -the min_avg_rate() function within your class would seem to be malfunctioning
I was watching a lesson on lynda.com and the code works for them but will not work when I try it. This is the exact code they use. Could use some help to why it is not working.
<?php
class Session
{
public $message;
function __construct(){
session_start();
$this->check_message();
}
public function get_message($msg="") {
if(!empty($msg)) {
// then this is "set message"
$_SESSION['message'] = $msg;
} else {
// then this is "get message"
return $this->message;
}
}
private function check_message() {
// Is there a message stored in the session?
if(isset($_SESSION['message'])) {
// Add it as an attribute and erase the stored version
$this->message = $_SESSION['message'];
unset($_SESSION['message']);
} else {
$this->message = "";
}
}
}
$session = new Session();
?>
and on the calling page
<?php
require_once("session_class.php");
function output_message($msg="") {
if (!empty($msg)) {
return "<p>$msg</p>";
} else {
return "";
}
}
if (isset($_SESSION['message'])) {
echo "session is set";
} else {
echo "session is not set";
}
$message = $session->get_message("working");
//$message = "Working";THIS WILL WORK
echo output_message($message);
?>
You haven't created an object instance on the calling page. Try this:
require_once("session_class.php");
$session = new Session();
EDIT
When you take out check_message() from the __construct, the SESSION is set because in your check_message() method, you have this:
unset($_SESSION['message']);
It basically destroys your session, that's why you see that message "session is not set".
If you want the session to be set, simply delete that line.