I am trying to figure out a way to do the following:
I want to make an action which will be loaded through ajax and also its the internal part of the page when page is reloaded.
I know this in ZEND framework by using View Helper, But don't know how to do in Kohana
I am new to Kohana.
EDIT:
Example of what I am trying to do http://www.espncricinfo.com/west-indies-v-india-2011/engine/current/match/489228.html?CMP=chrome
In above webpage when the whole web page is loaded the live score board is loaded with it. But when u click on "Refresh scoreboard" button only the live score board is replaced through ajax.
I want to create an action say action_scoreboard which will be used to bring scoreboard data. And action_index to load the whole page, but while in the view of action_index i need to call action_scoreboard.
Thanks
Not sure if this is the best way to do this, but this is how I like to handle the situation.
public function action_index($raw = 0) {
$records = Jelly::select('scores')->execute();
if ($raw == 0) {
$view = new View('purdy');
$view->records = $records;
$this->template->content = $view;
} else {
$this->auto_render = FALSE;
$this->request->headers['Content-Type'] = 'text/xml';
$view = new View('raw');
$view->records = $records;
$this->response->body($view->render());
}
}
### THE PURDY VIEW ###
<table>
<?
foreach ($records as $record) {
echo '<tr>';
echo '<td>'.$record->name.'</td>';
echo '<td>'.$record->value.'</td>';
echo '</tr>';
}
?>
</table>
### THE RAW VIEW ###
<?xml version="1.0" encoding="utf-8"?>
<scores>
<?
foreach ($records as $record) {
echo '<score>';
echo '<name>'.$record->name.'</name>';
echo '<value>'.$record->value.'</value>';
echo '</score>';
}
?>
</scores>
I used Kopjax - Pjax jQuery ajax module. Its code is available on gitgub
Related
I have a test function in controller which generates a form page.
public function testing()
{
$this->form_validation->set_rules('test', 'TEST', 'required');
if ($this->form_validation->run()) {
redirect($this->agent->referrer());
} else {
$data['title'] = 'Testing';
$data['message'] = (validation_errors()) ? validation_errors() : $this->session->flashdata('message');
$this->load->view('templates/header', $data);
$this->load->view('pages/nonmember/testing', $data);
$this->load->view('templates/footer');
}
}
The code of testing view as below
<div id="message"><?php echo $message; ?></div>
<?php echo form_open(base_url()."testing");?>
<p>
<?php echo form_input('test');?>
</p>
<p><?php echo form_submit('submit', 'Submit');?></p>
<?php echo form_close();?>
If users come from another page lets say About page to testing page i want after submitting form properly they get redirected back to About page. But it is not being possible as referer agent is staying at the testing page, so after submit it is staying there and not redirecting to About page.
All you need is:
redirect($_SERVER['HTTP_REFERER']);
add this line in your controller's testing function
$this->session->set_flashdata('url',$this->agent->referrer());
change this in the function testing
if ($this->form_validation->run()) {
redirect($this->session->flashdata('url'));
} else {
$this->session->set_flashdata('url',$this->agent->referrer());
//load the view
}
...
or you can also submit an hidden field like,
form_hidden('rURL', $this->agent->referrer());
then simply use its value in the controller.
if ($this->form_validation->run()) {
redirect($this->input->post('rURL'));
} else {
...
Not sure if it is the best solution or not , but i found the solution working perfectly.
We need to write the referrer address in a file and to redirect we need to read from that file.
first we need to load the file helper.
$this->load->helper('file');
if ($this->form_validation->run())
{
redirect(read_file('referrer.php'));
}
else
{
$referrer = $this->agent->referrer();
//need to check wrong input submission and page refresh
if ($referrer != "http://localhost/CIpractice2/testing" && !empty($referrer))
{
write_file('referrer.php', $referrer);
}
//show the form
}
Please refer to codeIgniter's file helper documentation
I am creating new pages for each of my categories in wordpress. The post editor has a custom field that allows the selection of a sector type, this gets applied to the post on update. The custom field key is: sector, for custom field meta value options lets use SectorA, SectorB and SectorC. I am using a custom post type called projects.
I followed the advice at this link http://weblogtoolscollection.com/archives/2008/04/13/how-to-only-retrieve-posts-with-custom-fields/
How can I change the query line in the code below so that it filters the loop by a Sector name, lets use SectorA. I'll then reuse the code on each template page changing the value to SectorB and SectorC on the other pages.
I think this needs changing somehow:
$customPosts->query('showposts=5§or=sectorA&post_type=projects' );
Currently it echos the sector value and description value successfully but is showing all the posts. So my attempt to limit it to sectorA using sector=sectorA doesn't seem to work?
This code is in functions.php:
function get_custom_field_posts_join($join) {
global $wpdb, $customFields;
return $join . " JOIN $wpdb->postmeta postmeta ON (postmeta.post_id = $wpdb->posts.ID and postmeta.meta_key in ($customFields)) ";
}
function get_custom_field_posts_group($group) {
global $wpdb;
$group .= " $wpdb->posts.ID ";
return $group;
}
And this code is on the Template Page:
<?php /* Begin Custom Field Posts */ ?>
<h2>Custom Posts</h2>
<ul>
<?php
global $customFields;
$customFields = "'sector', 'description'";
$customPosts = new WP_Query();
add_filter('posts_join', 'get_custom_field_posts_join');
add_filter('posts_groupby', 'get_custom_field_posts_group');
$customPosts->query('showposts=5§or=sectorA&post_type=projects' );//Uses same parameters as query_posts
remove_filter('posts_join', 'get_custom_field_posts_join');
remove_filter('posts_groupby', 'get_custom_field_posts_group');
while ($customPosts->have_posts()) : $customPosts->the_post();
$sector = get_post_custom_values("sector");
$description= get_post_custom_values("description");?>
<li><?php echo $sector[0]; ?></li>
<li><?php echo $description[0]; ?></li><br />
<?php endwhile; ?>
</ul>
<?php /* End Custom Field Posts */ ?>
Thanks for your help
May be this what you want
function get_custom_field_posts_join($join) {
global $wpdb, $customSector;
return $join . " JOIN $wpdb->postmeta postmeta ON (postmeta.post_id = $wpdb->posts.ID and postmeta.meta_key = 'sector' and postmeta.value = '$customSector') ";
}
and modification of page
$customSector='sectorA';//<--- insert this
add_filter('posts_join', 'get_custom_field_posts_join');
Try using this code.
<?php
$sector = get_post_meta($post->ID, "sector", false);
if ($sector[0]=="") { ?>
<!-- If there are no custom fields, show nothing -->
<?php } else { ?>
<div class="sector">
<h3>Title</h3>
<?php foreach($sector as $sector) {
echo '<blockquote><p>'.$sector.'</p></blockquote>';
} ?>
</div>
<?php } ?>
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; ?>
I am simply trying to show detail view page from table page
I have set up displaying list of pages via another function like this and works fine
> <a href="< ? php echo
> $ this -> url(array('controller'=>'page','action'=>'detail',
> 'id'=>$page->id));? >"> < ? php echo
> $this->escape($page->title);? ></a>
In my controller i added
public function detailAction()
{
$id = $this->_getParam('id', 0);
$page = new Application_Model_DbTable_Pages();
$this->view->myVar = $page->getPage($id);
}
and in view
> <?php print_r($this->myvar) ?>
This list
I just see blank page, how can i show detail page ?
Try:
<?php print_r($this->myVar) ?>
insted of myvar --> myVar. That is how You called Your variable in the action method.
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!