How to display error on PHP Plates templating engine - php

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;?>

Related

Using PHP sessions to send messages to the user

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?

A PHP Error was encountered "undefined variable already defined" but still not working

I received an error:
A PHP Error was encountered
Severity: Notice
Message: Undefined variable: data
Filename: controllers/c_verifylogin.php
Line Number: 17
This is the filename that has an error:
<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
class C_verifyLogin extends CI_Controller {
function __construct() {
parent::__construct();
//load session and connect to database
$this->load->model('m_login','login',TRUE);
$this->load->helper(array('form', 'url','html'));
$this->load->library(array('form_validation','session'));
}
function index() {
$this->form_validation->set_rules('studentid', 'studentid', 'trim|required|xss_clean');
$this->form_validation->set_rules('password', 'password', 'trim|required|xss_clean|callback_check_database');
if($this->form_validation->run() == FALSE) {
$this->load->view('v_login');
} else {
//Go to private area
redirect(base_url('c_home'), 'refresh');
}
}
function check_database($password) {
//Field validation succeeded. Validate against database
$studentid = $this->input->post('studentid');
//query the database
$result = $this->login->login($studentid, $password);
if($result) {
$sess_array = array();
foreach($result as $row) {
//create the session
$sess_array = array('studentid' => $row->studentid);
//set session with value from database
$this->session->set_userdata('logged_in', $sess_array);
}
return TRUE;
} else {
//if form validate false
$this->form_validation->set_message('check_database', 'Invalid username or password');
return FALSE;
}
}
}
/* End of file c_verifylogin.php */
/* Location: ./application/controllers/c_verifylogin.php */
and this is the view which the data is passed
<!DOCTYPE html>
<html>
<head>
<title>Simple Login with CodeIgniter</title>
</head>
<body>
<h1>Simple Login with CodeIgniter</h1>
<?php echo validation_errors(); ?>
<?php echo form_open('c_verifylogin/index');
echo form_label("StudentID: ");
echo form_input("studentid");
echo br();
echo form_label("Password: ");
echo form_password("password");
echo br();
echo form_submit("","Login");
echo form_close();
?>
</body>
</html>
I've been searching for the problem for hours, and I still don't know what's wrong with it. Can someone help?
Here in your code clearly show that you didn't define $data variable.
So you have 2 options either define $data as array like
$data = array();
or simply load the view without passing any variable like
$this->load->view('v_login');
I hope it will help you.
$data variable is not defined here..define it with some value of if you want to pass it else don't pass
$data to view call...
if($this->form_validation->run() == FALSE) {
$this->load->view('v_login',$data);
} else {
//Go to private area
redirect(base_url('c_home'), 'refresh');
}
}
Either you have to define $data
$data = array('something');
$this->load->view('v_login',$data);
or
remove $data
$this->load->view('v_login');

CakePHP Post parameter

I've some problem in cakephp to send/receive an input form
// /View/Services/add_services.ctp
....
<?php echo $this->Form->create('Service', array('action'=>'addServices'))?>
<?php echo $this->Form->input("service_name", array('label'=>false, 'div'=>false, 'class'=>"umstyle5"))?>
<?php echo $this->Form->Submit(__("Add service Type"))?>
<?php echo $this->Form->end();?>
// /Controller/ServicesController
....
public function addServices(){
....
$service_name = $_POST[service_name];
....
}
The problem is that I receive this error:
Undefined index: service_name [APP/Controller/ServicesController]
What is wrong?
Thanks!!
Use $this->request->data.
public function addServices(){
....
$service_name = $this->request->data['Service']['service_name'];
....
}
I suggest you please check the Documentation properly,
There are clearly mentioned that we can fetch data like...
//Controller/RecipesController.php:
public function edit($id = null) {
if (empty($this->request->data)) {
$this->request->data = $this->Recipe->findById($id);
} else {
// Save logic goes here
}
}

Sending a variable to the view which is used in controller with phalconPHP

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);

Warnin:Illegal offset type [CORE\Cake\Model\Model.php, line 2734] came on click of login in PHP

I created a simple login form using Cake Php.When i click on the Login button one Warning appear
Illegal offset type [CORE\Cake\Model\Model.php, line 2734
I have use link as a reference http://bakery.cakephp.org/articles/SeanCallan/2007/04/17/simple-form-authentication-in-1-2-x-x
Code of Login.ctp
Login
<?php echo $this->Form->create('User', array('action' => 'login'));?>
<?php echo $this->Form->input('username');?>
<?php echo $this->Form->input('password');?>
<?php echo $this->Form->submit('Login');?>
<?php echo $this->Form->end(); ?>
2. modal file
find(array('username' => $data['username'], 'password' => md5($data['password'])), array('id', 'username'));
if(empty($user) == false)
return $user['User'];
return false;
}
}
?>
3.controller file
<?php
App::uses('AppController', 'Controller');
class UsersController extends AppController
{
var $name = "Users";
var $helpers = array('Html', 'Form');
var $components = array("Auth");
function index()
{
}
function beforeFilter()
{
$this->__validateLoginStatus();
}
function login()
{
if(empty($this->data) == false)
{
if(($user = $this->User->validateLogin($this->data['User'])) == true)
{
$this->Session->write('User', $user);
$this->Session->setFlash('You\'ve successfully logged in.');
$this->redirect('index');
exit();
}
else
{
$this->Session->setFlash('Sorry, the information you\'ve entered is incorrect.');
exit();
}
}
}
function logout()
{
$this->Session->destroy('user');
$this->Session->setFlash('You\'ve successfully logged out.');
$this->redirect('login');
}
function __validateLoginStatus()
{
if($this->action != 'login' && $this->action != 'logout')
{
if($this->Session->check('User') == false)
{
$this->redirect('login');
$this->Session->setFlash('The URL you\'ve followed requires you login.');
}
}
}
}
?>
Why that happened.i am new in this.Some developers in PHP chat room suggest me to not use that Cake PHP. Any help is appreciated
Illegal offset type means that you tried to use an object or an array to index an array:
$x = stdClass;
$a = array(1,2,3,4);
$a[$x]; // illegal offset type
Check your code for possible places where you've taken user input (which could be an array of values even though you thought it's just one value) and used it in some function that expected just a value.
If that Cake internal function expected a value and tried to use it as the offset of an array, this message would appear.
Obs
The only place I notice in your code that passes a parameter (and not literal string values) is here:
$this->User->validateLogin($this->data['User']))
Do a var_dump on $this->data['User'] and see what's in it perhaps it's an array and you should've extracted just $this->data['User']['id'] I don't know, i haven't played that much with Cake.

Categories