Error in view file - zend-framework

I'm new to zend framework.I'm getting the following error when trying to view the page
Fatal error: Using $this when not in object context in D:\xampp\htdocs\neemjobs\application\views\scripts\register\index.phtml on line 1
class RegisterController extends Zend_Controller_Action
{
public function init()
{
/* Initialize action controller here */
}
public function indexAction()
{
$this->view->pageTitle = "Zend_Form Example";
$this->view->bodyCopy = "<p >Please fill out this form.</p>";
$form = new forms_ContactForm();
$this->view->form = $form;
}
}
My View is
<?php echo $this->pageTitle ;?>
<?php echo $this->bodyCopy ;?>

This is totally correct (on my Zend Framework installation goes perfectly, I just don't understand "in which way" are you using the Form... but, anyway, it works, so the "bug" is not there...

Related

Zend Framework translate language text

I have some translation code which is working fine.
<?php echo $this->translate("54"); ?>
Outputs
Hello World
is it possible to output instead of above
<div class='lang' id='54'>Hello World</div>
Later using jquery I would like to manipulate the div.
create a custom view helper named MyTranslate extends \Zend\I18n\View\Helper\Translate then override the _invoke method :
public function __invoke($message, $textDomain = null, $locale = null)
{
$t = parent::__invoke($message, $textDomain , $locale);
//change the value of $t however you wnat
return $t;
}
if you don't what to change your code where ever you have used translate register this new view helper as translate and not my_translate
If you use Zend1, you can use a view helper like this:
Create a Helper directory in your library
for example, in my case I have this directory:
library/DoyDoy/Helper/
Create your helper like this:
library/DoyDoy/Helper/TranslateID.php
<?php
class DoyDoy_Helper_TranslateID extends Zend_View_Helper_Abstract
{
public function translateID($id)
{
return '<div class=\'lang\' id=\'' . $id . '\'>'. $this->view->translate($id) . '</div>';
}
}
Add your Helper in the bootstrap:
protected function _initDoyDoyView(){
$this->bootstrap('view');
$view = $this->getResource('view');
$view->addHelperPath('DoyDoy/Helper/', 'DoyDoy_Helper');
}
In your view, call the helper like this:
<?php echo $this->translateID("54");?>
This should display:
<div class='lang' id='54'>Hello World</div>
I hope it will help you :)

Zend pass variable from plugin to view

In plugin I try $this->view->menu = $menu; , but in view I try <?php var_dump($this->menu); ?> and get NULL
Maybe are solution to pass variable from plugin to view ?
you can use like below
First : Without using helpers or plugins do :
Zend_Layout::getMvcInstance()->assign('whatever', 'foo');
After this you can use the following in your layout:
<?php echo $this->layout()->whatever; ?>
This will print "foo".
OR
Second :
<?php
class My_Layout_Plugin extends Zend_Controller_Plugin_Abstract
{
public function preDispatch(Zend_Controller_Request_Abstract $request)
{
$layout = Zend_Layout::getMvcInstance();
$view = $layout->getView();
$view->whatever = 'foo';
}
}
then register this plugin with the front controller, e.g.
Zend_Controller_Front::getInstance()->registerPlugin(new My_Layout_Plugin());

unset session variable in zend view

I ll reframe my question based on some research I have done?
I need to store lot of errors separately like $_SESSION['client_error'],$_SESSION['state_error'] etc.
According to zend documentation do I have to store it like this for each error?
$client_error = new Zend_Session_Namespace(''client_error);
$state_error = new Zend_Session_Namespace('state_erro'); and so on?
This is my code in the controller.
I am storing it as
$this->view->state_error_message=$state_error;
After I echo $this->state_error in the view I want to unset it.
Ok here are few more things I tried:
In the controller in policyInfoAction:
session_start();
$error_message = new Zend_Session_Namespace('error_message');
$error_message="TEST";
$this->view->error_message=$error_message;
$this->_redirect('/pdp/client-info/');
In the view in client-info:
session_start();
<?php echo $this->error_message; ?>
This returns nothing.
Ok this is my updated code:
public function clientInfoAction()
{
$errors = new Zend_Session_Namespace('errors');
// get the error arrays
$client_errors = (isset($errors->client_error)) ? $errors->client_error : array();
$state_errors = (isset($errors->state_error)) ? $errors->state_error : array();
unset($errors->client_error, $errors->state_error); // delete from the session
// assign the values to the view
$this->view->client_errors = $client_errors;
$this->view->state_errors = $state_errors;
}
public function policyInfoAction()
{
if (count($arrErrors) > 0)
{
// The error array had something in it. There was an error.
$strError="";
foreach ($arrErrors as $error)
{
$strError="";
$errors->client_error = array();
$errors->state_error = array();
foreach ($arrErrors as $error)
{
$strError .= $error;
// to add errors to each type:
$errors->client_error['client_error'] = $strError;
$errors->client_error[] = $strError;
$this->_redirect('/pdp/client-info/');
}
}
}
When i echo $this->client_errors I get 'Array'
Here is some advice and suggestions that can hopefully get you on the right track.
First, when using Zend_Session and/or Zend_Session_Namespace, you never want to use PHP's session_start() function1. If you start a session with session_start(), and then try to use Zend_Session, it will throw an exception that another session already exists.
Therefore, remove all session_start() calls from your Zend Framework application.
Second, you mentioned you had a lot of messages you need to store, so this may not be the right thing for you, but see the FlashMessenger action helper. This allows you to set a message in a controller, and then access it on the next page request. The messages only live for one page hop, so after the next page load, they are deleted. You can store many messages with the FlashMessenger, but your access to them is not very controlled. You could use multiple flash messengers each in differen namespaces also.
To solve your problem in particular, you could just do something like this:
// in controller that is validating
$errors = new Zend_Session_Namespace('errors');
$errors->client_error = array();
$errors->state_error = array();
// to add errors to each type:
$errors->client_error['some_error'] = 'You had some error, please try again.';
$errors->client_error['other_error'] = 'Other error occurred.';
$errors->client_error[] = 'Other error, not using a named key';
$errors->state_error[] = MY_STATE_PARSING_0;
What is happening here is we are getting a session namespace called errors creating new properties for client_error and state_error that are both arrays. You don't technically have to use multiple Zend_Session_Namespaces.
Then to clear the messages on the next page load, you can do this:
// from controller again, on the next page load
$errors = new Zend_Session_Namespace('errors');
// get the error arrays
$client_errors = (isset($errors->client_error)) ? $errors->client_error : array();
$state_errors = (isset($errors->state_error)) ? $errors->state_error : array();
unset($errors->client_error, $errors->state_error); // delete from the session
// assign the values to the view
$this->view->client_errors = $client_errors;
$this->view->state_errors = $state_errors;
See also the source code for Zend_Controller_Action_Helper_FlashMessenger which can give you some idea on managing data in session namespaces.
I don't know if this will help you or not but here is the code for a controller that just takes an id from a form a gathers data based on that id an assigns that data to the session (to be used throughout the module) and then unsets that data when appropriate. and Never leaves the Index page.
<?php
class Admin_IndexController extends Zend_Controller_Action
{
//zend_session_namespace('location')
protected $_session;
/**
*set the layout from default to admin for this controller
*/
public function preDispatch() {
$this->_helper->layout->setLayout('admin');
}
/**
*initiaize the flashmessenger and assign the _session property
*/
public function init() {
if ($this->_helper->FlashMessenger->hasMessages()) {
$this->view->messages = $this->_helper->FlashMessenger->getMessages();
}
//set the session namespace to property for easier access
$this->_session = new Zend_Session_Namespace('location');
}
/**
*Set the Station and gather data to be set in the session namespace for use
* in the rest of the module
*/
public function indexAction() {
//get form and pass to view
$form = new Admin_Form_Station();
$form->setAction('/admin/index');
$form->setName('setStation');
$this->view->station = $this->_session->stationName;
$this->view->stationComment = $this->_session->stationComment;
$this->view->form = $form;
try {
//get form values from request object
if ($this->getRequest()->isPost()) {
if ($form->isValid($this->getRequest()->getPost())) {
$data = (object)$form->getValues();
//set session variable 'station'
$this->_session->station = $data->station;
$station = new Application_Model_DbTable_Station();
$currentStation = $station->getStation($this->_session->station);
$this->_session->stationName = $currentStation->station;
$this->_session->stationComment = $currentStation->comment;
//assign array() of stations to session namespace
$stations = $station->fetchAllStation();
$this->_session->stations = $stations;
//assign array() of bidlocations to session namespace
$bidLocation = new Application_Model_DbTable_BidLocation();
$bidLocations = $bidLocation->fetchAllBidLocation($this->_stationId);
$this->_session->bidLocations = $bidLocations;
$this->_redirect($this->getRequest()->getRequestUri());
}
}
} catch (Zend_Exception $e) {
$this->_helper->flashMessenger->addMessage($e->getMessage());
$this->_redirect($this->getRequest()->getRequestUri());
}
}
/**
*Unset Session values and redirect to the index action
*/
public function changestationAction() {
Zend_Session::namespaceGet('location');
Zend_Session::namespaceUnset('location');
$this->getHelper('Redirector')->gotoSimple('index');
}
}
just to be complete i start the session in the bootstrap. On the theory that if I need it great if not no harm.
protected function _initsession() {
//start session
Zend_Session::start();
}
this is all the view is:
<?php if (!$this->station): ?>
<div class="span-5 prepend-2">
<?php echo $this->form ?>
</div>
<div class="span-10 prepend-2 last">
<p style="font-size: 2em">Please select the Station you wish to perform Administration actions on.</p>
</div>
<?php else: ?>
<div class="span-19 last">
<?php echo $this->render('_station.phtml') ?>
</div>
<?php endif; ?>

Start execution from indexAction() in IndexController in ZEND Framework

In indexAction() method of IndexController I have called the method of model which returns the list of employees(employeeList) from database.And then add this this employeeList to $view and then call $view->render('index.phtml') and index .phtml shows the employeeList.The code is ad follows:
IndexController.php
<?php
require_once('../Zend/Controller/Action.php');
require_once('../models/HRModel.php');
require_once('../Zend/View.php');
class IndexController extends Zend_Controller_Action
{
protected $hrModel;
public function init()
{
$this->hrModel = new Application_Model_HRModel();
}
public function indexAction()
{
$view = new Zend_View(array('scriptPath' =>'../views'));
$view->employeeList = $this->hrModel->queryAllEmployees();
echo $view->render('index.phtml');
}
}
Application_model_HRModel.php
<?php
require_once('Zend/Db.php');
require_once('Zend/Config/Ini.php');
class Application_Model_HRModel
{
protected $db=null;
public function queryAllEmployees() {
return $this->db->fetchAssoc("select comment from guestbook");
}
}
index.phtml
foreach ($this->employeeList as $emp):
extract($emp);
echo '$EMPLOYEE_ID';
echo $comment;
endforeach
Now I want to start the execution from indexAction() method.But how to do this?What should be the url to be entered in browser?In request parameter the controller will be IndexController and action will be indexAction.So Kindly help me in resolving this issue.
To execute this action, you need to call the Index Controller with index Action. So you use www.foo.bar/index/index or simple www.foo.bar.
If this dont work, you have maybe a error in your confoguration.
Or did i mistake your question?
How did you configure your PHP Error handling? Maybe you have a PHP error that is not displayed.

Embedding persistent login form Zend

I've seen this question asked already - but none of the answers really gelled for me, so I'm asking again: I want to embed a persistent login form (which will change into a nav bar if logged in) in the header bar for a site. Effectively, I want to be able to inject some controller logic into the layout.
After much research, I can see several ways that might achieve this - none of which seem ideally suited.
View Helpers seem suited to adding a suite of methods to the Zend_View object - but I don't want to write conditional code in the layout.phtml to trigger a method. Action helpers would help me remove that functionality and call it from a Controller - but that seems to be in poor favour from several quarters. Then there are plugins, which might be well suited in the dispatch/authentication loop.
So, I was hoping someone might be able to offer me some guidance on which way might best suit my requirements. Any help is greatly appreciated.
For those of you with a similair issue, this is how I ended up solving it (I'm using layout btw)
I registered a view helper in the Bootstrap:
protected function _initHelpers(){
//has to come after view resource has been created
$view = $this->getResource('view');
// prefix refers to the folder name and the prefix for the class
$view->addHelperPath(APPLICATION_PATH.'/views/helpers/PREFIX','PREFIX');
return $view;
}
Here's the view helper code - the actual authentication logic is tucked away in model code. It's a bit clumsy, but it works
class SB_UserLoginPanel extends Zend_View_Helper_Abstract {
public function __construct() {
$this->user = new SB_Entity_Users();
$this->userAccount = new SB_Model_UserAccount();
$this->request = Zend_Controller_Front::getInstance()->getRequest();
$this->form = $this->makeLoginForm();
$this->message='';
}
//check login
public function userLoginPanel() {
if(isset($_POST['loginpanel']['login'])) {
$this->processLogin();
}
if(isset($_POST['loginpanel']['logout'])) {
$this->processLogout();
}
$auth = Zend_Auth::getInstance();
if ($auth->hasIdentity()) {
$this->loginPanel = $this->getUserNav();
} else {
$this->loginPanel = $this->getLoginForm();
$this->loginPanel .= $this->getMessages();
}
return $this->loginPanel;
}
private function processLogin() {
if($this->form->isValid($_POST)){
$logindata = $this->request->getPost('loginpanel');
if($this->user->login($logindata['email'],$logindata['password'])) {
Zend_Session::rememberMe();
$redirect = new Zend_Controller_Action_Helper_Redirector();
$redirect->goToUrl('/account/');
return $this->getUserNav();
}else {
$this->message = '<p id="account_error">Account not authorised</p>';
}
}else {
$this->form->getMessages();
}
}
private function processLogout() {
if(isset($_POST['loginpanel']['logout'])) {
$this->user->logout();
$request_data = Zend_Controller_Front::getInstance()->getRequest()->getParams();
if($request_data['controller']=='notallowed') {
$redirect = new Zend_Controller_Action_Helper_Redirector();
$redirect->goToUrl('/');
}
}
}
private function makeLoginForm() {
}
private function getLoginForm(){
return $this->form;
}
private function getMessages(){
return $this->message;
}
private function getUserNav(){
//return partial/render
}
}
I then call this from the relevant part of the markup in the layout.phtml file.
<?php echo $this->doctype(); ?>
<head>
<?php
echo $this->headLink() ."\n";
echo $this->headScript() ."\n";
echo $this->headMeta() ."\n";
?>
<title><?php echo $this->escape($this->title) ."\n"; ?></title>
</head>
<div id="masthead">
<div id="userLoginPanel">
<?php echo $this->userLoginPanel(); ?>
</div>
</div>
<!--rest of layout-->
In principle, this should be an action helper, but after reading some less than favourable articles regarding Zend Action Helper - I opted for this method which did the trick.
Hope that helps!