Greets.
{{Solved}}
In order to get POST data you MUST use $this->formHidden in order to hold all the data. Even though variables are inside the they don't get passed if they aren't in some sort of form item.
I am unable to access post data in ZEND.
Path of User -
START
INDEX PAGE
->Submit Page
->Pay Page
I created a controller, extended the Zend Controller, and added an action called payAction. The user can go from the Index Page to the Submit Page. After I have all their data inside variables, I used a form and a submit button to go to the "pay page". However, I cannot get any of the POST data.
public function payAction()
{
$data = $this->getRequest();
}
I have tried putting getRequest, getParam, getRawBody inside that controller function.
In the page itself I have tried.
echo 'Hello';
echo $request;
echo $data;
echo $_POST['payZip'];
echo $_POST['data'];
echo $_POST[$data];
echo $request;
echo $this->values['payZip'];
echo $payZip;
echo $this->values['shippingDone'];
echo $stuff;
Is there ANYTHING I can place in my controller or in my view in order to get my post data? I used a form method="post" and a button and it DOES allow me to get to the page. I can see Hello. But NONE of the post data is available.
Any assistance would be appreciated.
Thank you.
-- Update
$data = $this->getRequest();
$param = $this->_request->getParam('payZip');
if($this->getRequest()->isPost())
{
print_r($this->_getAllParams());
echo $param;
}
Doing that gives me -
HelloArray ( [controller] => wheel [action] => pay [module] => default [shipping] => UPS Ground [payPal] => Secure Payment System )
But I still can't print payZip... I did echo and nothing comes out.
To get parameters from Zend Framework you need to do this in the Action Controller:
$data = $this->_request->getParams();
You can also get individual params like this
$param = $this->_request->getParam('payZip');
What it appears your doing wrong is you're only getting the "request object". You need to then call that objects method to get the request data.
Here's some simple code I often use when testing parameters:
public function indexAction()
{
#::DEBUG::
echo '<pre>'; print_r($this->_request->getParams()); echo '</pre>';
#::DEBUG::
}
This will show all your parameters. What you will notice is that you will also get the names of the Module, Controller and Action with your params.
EDIT
Ps. If you're trying to use the parameter in the view script you need to do this:
echo $this->data['payZip'];
echo $this->param;
In your Action Controller, you save your data to the "view" object by doing this:
$this->view->myVariable = 'Hello';
But when you're in a view script, you are IN the view script, so $this represents $this->view from the action controller.
So, you access the variable like this:
echo $this->myVariable;
Wrapping everything into a bigger code chunk for understanding:
Your Controller
public function indexAction()
{
// get all parameters and pass them to the view
$this->view->params = $this->_request->getParams();
// get an individual parameter and pass it to the view
$this->view->payZip = $this->_request->getParam('payZip');
}
Your View Script
<!-- Dump all parameters -->
<pre><?php print_r($this->params); ?></pre>
<!-- Print payZip -->
<p>My PayZip is: <?php echo $this->payZip; ?></p>
<!-- Print payZip from full parameter array -->
<p>My PayZip (array) is: <?php echo $this->data['payZip']; ?></p>
I hope that helps!
Related
I edit a row on the Post table or add a new row to it from edit() function in PostsController. The function looks like this:
public function edit($id = null) {
// Has any form data been POSTed?
if ($this->request->is('post')) { //Replaced 'post' by 'get' in this line
// If the form data can be validated and saved...
if ($this->Post->save($this->request->data)) {
// Set a session flash message and redirect.
$this->Session->setFlash('Updated the Post!');
return $this->redirect('/posts');
}
}
// If no form data, find the post to be edited
// and hand it to the view.
$this->set('post', $this->Post->findById($id));
}
I simply replaced 'post' by 'get' to see what would happen and it went on creating new rows without even taking me to the form. I still get the flash message 'Updated the Post!', but without taking any form data.
If the code in edit.ctp is required, here it is:
<?php
echo $this->Form->Create('Post');
echo $this->Form->input('id', array('type' => 'hidden','default'=>$post['Post' ['id']));
echo $this->Form->input('title',array('default'=>$post['Post']['title']));
echo $this->Form->input('body',array('default'=>$post['Post']['body']));
echo $this->Form->end('Update');
?>
Any thoughts on why this might be happening?
Edit: Added CakePHP Version
I am using CakePHP 2.4.5
What you are doing makes no sense.
Why would you want to switch the "post" by "get" here?
Of course it will then generate new rows, as you effectively trigger a save on each page load (GET).
Don't do that.
The code you had there was just fine - IF you also took PUT into consideration.
For edit forms, it is not a post, but:
if ($this->request->is('put')) {}
PS: If you want to make sure it always works for both add/edit, use
if ($this->request->is(array('post', 'put')) {}
But NEVER replace it with "get".
i am trying to populate two form fields from data that is retrieved from a database, in order for the user to update them. The table is called records and it is quite simple:
Record_ID
title
content
My model:
function get_data()
{
$r = $this->uri->segment(3);
$query = $this->db->get_where('records', array('Record_ID' => $r));
return $query->result();
}
My controller:
function set_values()
{
$data = $this->entries_model->get_data();
$this->load->view('update_view', $data);
}
and my update record view:
<?php
echo form_open('site/update',$data);?>
Title:
<?php echo form_input('title',set_value('title'));?>
Content:
<?php echo form_input('content',set_value('content'));
echo form_submit('submit', 'Submit');?>
<?php echo form_close();?>
The problem is that i get the following error:
A PHP Error was encountered
Severity: Notice
Message: Undefined variable: data
Filename: views/update_view.php
Line Number: 10
My question is twofold:
How do i access this data in my view form and
how do i populate the respective fields with it.
I am new to Codeigniter, my questions may look simplistic but any help would be appreciated. Thanks in advance.
There are a few things going on here:
$data is an array or object that is passed to a view. It's ELEMENTS are then available as variables in the view. So, $data['myelement'] = 'somevalue' in the controller would be accessed as $somevalue in the view.
If you pass a 2nd parameter to the form_open() method, it is expected to be a key/value pair of attributes for the tag that will be generated. like, array('class' => 'form_class', 'id' => 'form_id')
If you want to set the values of your form inputs, use the view helper function set_value(). In your case, use the controller to set elements in the $data array you'll pass to the view. $data['form_values'] = array('title' => $title, 'content' => $content);
Then, in the view:
You should pass a array to your view file. So replace:
$data = $this->entries_model->get_data();
with:
$data['entries_data'] = $this->entries_model->get_data();
and on your view file replace:
echo form_open('site/update',$data);?>
with:
echo form_open('site/update',$entries_data);?>
first you need to pass data in proper way
replace
$data = $this->entries_model->get_data();
with:
$data['data'] = $this->entries_model->get_data();
for setting value in set_value you need to do the in-line condition check to check either data is an object or not if object then put value other wise just empty
<?php echo form_input('title',set_value((is_object($data)?$data->title:'')));?>
you have to do the same thing for your all form fields
Jcory has answered your question but let me add a little to it.
In you model instead of return $query->result(); do this return $query->row(); this is because using returning a return object requires that you should loop through the resultset in your view
Instead of $data = $this->entries_model->get_data(); do this $data['entry'] = $this->entries_model->get_data();
In your view do this <?php echo form_input('title',set_value('title',$entry->title));?>
I hope these changes may solve the problem
Here is the code in my controller:
$this->view->myArray = array();
$this->view->test = "";
$out = $this->view->partialLoop('tab/partial.phtml', $data);
echo $this->view->test; // Output: This works
echo count($this->view->myArray); // Output: 0
And the partial partial.phtml:
$v->test = $this->partialLoop()->view;
$v = "This works";
echo $v->test; // Output: This works
$v->myArray[] = "hello";
echo count($v->myArray); // Output: 0
I don't think that accessing view variables from a partialLoop is a wonderful idea. That aside, why doesn't it work for my array variable?
it doesn't work because you don't have access to the view variables in the partial. You have access to the data you pass to the partial.
$out = $this->view->partialLoop('tab/partial.phtml', $data);
This line of code would have access to the information contained in $data.
So this code in your current partial is basically meaningless:
$v = $this->partialLoop()->view; //you choose to assign view data to the partial, and I don't think it's working as expected.
//By not passing any args to the partial you have at least some access to the view object.
$this->view->test = "This works";//assign data to view locally
echo $v->test; // you seem to be echoing out locally assigned data
$v->myArray[] = "hello";//you didn't assign this to the view
echo count($v->myArray); // myArray probably doesn't exist in this context or dosen't work as expected. If you make this an associative array it might work.
I don't think I've ever seen partials used in quite this manner before. The point of the partial is to establish a different variable scope for a specific portion of the view.
The partial and partialLoop are view helpers so the only action you need to take in your controller (data may be or come from a model as well) is to make available any data you want to use in your partials as well as any data you want available in your normal view scope.
//in a controller
public function userAction() {
$model = Application_Model_DbTable_User();//Table columns = id, name, role
$this->view->partailData = $model->fetchAll();//assign data to view that we want to use in partial, should be an array or object.
}
//in a view script
<?php
//pass the path to the partial as the first arg and the data to be displayed as the second arg
echo $this->partialLoop('/path/to/partial.phtml', $this->partialData);
//we could pass data explicitly as well
echo $this->partial('/path/to/partial.phtml', array('id'=>1,'name'=>'jason','role'=>'user'));
?>
//now for our partial.phtml
//this could be used a simple partial or as a partialLoop
<p>My name is <?php echo $this->name ?>.</p>
<p>My data file id is <?php echo $this->id ?>.</p>
<p>My access control role is <?php echo $this->role ?>. </p>
<!-- name, id and role would be column names that we retrieved from the database and assigned to the view -->
To use a partial or partialLoop you need to pass an array of some type or an object that implements toArray().
[EDIT]
Clean up your code your still in left field.
//controller code
$this->view->myArray = array();
//view code
<?php $v = $this->partial()->view ?>
<?php $v->myArray[] = 'newName' ?>
<?php Zend_Debug::dump(count($this->partial()->view->myArray)) ?>
//my output =
int(1)
I don't seem to be able to pass the view any further then this, if I assign to an actual partial script and attempt to output the view object errors are thrown:
//my view again
<?php echo $this->partial('partial.phtml', $this->partial()->view) ?>
//This and attempts similar result in the error
/*Catchable fatal error: Object of class Zend_View could not be converted to string in E:\www\home-local\application\views\scripts\partial.phtml on line 1*/
//when the partial.phtml looks like
<?php echo $this />
//however when I access the data available in the view
<?php echo $this->myArray[0] ?>
//the result works and the output is
newName
it looks like an empty partial() (partialLoop()) call will give you access to the view object, when you already have access to the view object. If you leave the scope of the view object you will have only the access available to your current scope as provided by __get() and __call().
I hope I was able to explain this enough to help.
maybe you cant set the value of $v or the item because its private or static or discarded
also from the code you posted its using recursion which could make it a lot more breakable (ie the controller is referencing the views data, and the view is setting it or hasnt set it or has set it twice)
agreed i dont think accessing view var's from a partialLoop is a good idea.
edit:
$this->view->assign('variablename', $my_array);
I think the variable is otherwise "lost" on the Rerender, so work on your variables in your controller, and before you are done assign them to the view. I wouldn't really do array operations on $this->view->myArray
I am building an admin module and need to process a form but am having troubles getting the variables to POST and am just redirected to the dashboard. The form looks like this :
<form name="notes" action="<?php echo Mage::helper("adminhtml")->getUrl("foo/index/processnotes/");?>" method="post">
<input type="hidden" name="another_form_key" value="<? echo $this->getFormKey(); ?>" />
I am doing it that way because the secure keys are turned on for admin. It gives me a url like :
foo/index/processnotes/key/4745f5fbb9c168778958d5d4a4c2c0ef/
In the controller I have:
public function processnotesAction(){
$model = Mage::getModel('foo/process');
// I am not sure how I am supposed to send $_POST values here
}
and in Package/foo/Model/Process.php
I would hope to be able to process the POST variables from my form in here but I can not see what is wrong and I am just sent to dashboard.
<?php
class Package_foo_Model_Process extends Mage_Core_Model_Abstract
{
public function noteProcess() {
$test = $_POST['myValue'];
echo $test;
}
}
Update
After reading the answers I wanted to add a bit more of what my real code is doing and how I am using $_POST. I was setting up a simple example to just get the form to post but realizing there are probably many things I am doing wrong in Magento.
$query="INSERT INTO `notes_value` ( `color`, `the_id`, `the_value` ) VALUES ";
$sku = $_POST['color'];
array_pop($_POST);
foreach ($_POST AS $key => $value) {
$values[] = "('$sku', '$id', '$value')";
}
$query .= implode(', ', $values) . ';';
The dream is I could $resource->getConnection('core_write'); to actually insert this into the database but feeling less optimistic with how it is going so far.
Usually when you are getting redirected to the dashboard because your key is not recognised. I normally would use the following syntax
<input name="form_key" type="hidden" value="<?php echo Mage::getSingleton('core/session')->getFormKey() ?>" />
Also, I would be inclined to disable admin keys to verify whether that is your issue.
Next, never, ever use $_POST with Magento, all variables are accessible (cleanly and securely). POST information is accessible globally (not just in a controller), however you can still set variables in your model from the controller like this:
public function processnotesAction(){
$model = Mage::getSingleton('foo/process');
$model->setData('postdata', $this->getRequest()->getPost() );
}
Then accessing them from your model with:
$this->getData();
$this->getMyPostedField();
Or you could just use this in your Model
Mage::app()->getRequest()->getPost();
Mage::app()->getRequest()->getParam('myargument');
getPost can also take a parameter to fetch a single POST value - but it does not get GET values. getParam will return both GET and POST values alike.
Request params are accessible via the request object, Mage_Core_Controller_Request_Http. Example usage:
$request = $this->getRequest();
$params = $request->getParams();
$someParam = $request->getParam('param_key');
// or $params = $request->getPost();
You then need to set the data on your model and call $model->save().
If your controller extends ActionController, then the preDispatch() function is the one responsible for redirecting you to the dashboard (and checking for valid form key..).
I suggest you put Mage::log debug info into ActionController's preDispatch function, that might help identify what's going on?
I was gonna post a comment, but don't have high enough reputation.
(maybe update your post or comment on the answer that helped you, to see how you solved it (or not))
in the controller i have :
$paginator = Zend_Paginator::factory($mdlPost->getPosts($this->moduleData->accordion, 'name ASC'));
if(isset($params['cities'])) {
$paginator->setCurrentPageNumber(intval($params['cities']));
}
$paginator->setItemCountPerPage(4);
$this->view->posts = $paginator;
in the view's i have some thing like this :
if ($this->posts != null) {?>
<div id="cities_accord" class="news">
<?php echo $this->partialLoop('partials/post-min.phtml', $this->posts); ?>
</div>
<?php echo $this->paginationControl($this->posts,
'Sliding',
'public/pagination_cont.phtml');
}
the partial/post-min.phtml
<?php
$color = array(1=>'spring',2=>'summer',3=>'autumn',4=>'winter');
?>
<div id='<?php echo $color[$this->partialCounter] ?>' class="accordion_post">
<?php
$link = Digitalus_Uri::get(false, false, array('openCity' =>
$this->id));//$color[$this->partialCounter]));
?>
<h1 class="accordion_post_title"><?php echo $this->title ?></h1>
<p><?php echo $this->teaser ?> <i>read more</i></p>
</div>
the pagination_cont.phtml taken from this link zend ( http://framework.zend.com/manual/en/zend.paginator.usage.html )
will show links that will pass params to the controller to fetch the corresponding whole page which is working alright for now
but i want to change this so that i will be able ajaxify the returned ( i.e. only a single paginated value rather than reloading the whole page ) results how can i do that using jquery and what should i change ..
** EDIT: it would be nice to have a fail-save ,if possible, for browsers(users) that disabled javascript to see the same thing by reloading the page (i.e. keeping the current status for if(javascript_not_enabled ))**
This is what I've done in the past.
First, setup the AjaxContext action helper to enable the html context on your controller action.
Add a .ajax.phtml view that just contains the section of markup that may be replaced via AJAX as well as the pagination control links. You can probably just copy this out of your normal view. Replace that section in your normal view with something like
<div id="reloadable-content">
<?php echo $this->render('controller/action.ajax.phtml') ?>
</div>
This will ensure that your initial and any non-AJAX requests will still include the right content. The <div> id is purely for referencing the loadable block in JavaScript.
Also make sure you include your JS file (using headScript) in the normal view only.
Now, in your JS file, unobtrusively add the appropriate event binding to the paginator links. As you'll be replacing the pagination control section in order to reflect the correct current page and other links, it's probably best to do this using the jQuery live binding. I'm also assuming you'll wrap the pagination control with some kind of identifiable element (<div class="pagination-control"> for example)
$('.pagination-control').find('a').live('click', function(e) {
var link = $(this);
$('#reloadable-content').load(link.attr('href'), { format: 'html' });
return false;
});
Keep in mind that in using this method, you will lose the ability to navigate the paged requests using the normal back / forward browser buttons. You will also lose the ability to bookmark pages directly (though you could always provide a permanent link to the current page as part of the AJAX loaded content).
You can use something like the jQuery history plugin if you're really concerned but that will require more client-side work.
Another caveat is that the above will only work with pagination links. If you want to use a form with dropdown page selection, you need to add another event handler for the submission.
GOT IT and big Thanks to #Phil Brown :
in the controller int() change the response type to json
class NewsController extends Zend_Controller_Action
{
public function init()
{
$contextSwitch = $this->_helper->getHelper('contextSwitch');
$contextSwitch->addActionContext('list', 'JSON')
->initContext();
}
// ...
}
public listAtcion() {
// .............
$paginator = Zend_Paginator::factory($mdlPost->getPosts($this->moduleData->accordion, 'name ASC'));
if(isset($params['cities'])) {
$paginator->setCurrentPageNumber(intval($params['cities']));
}
$paginator->setItemCountPerPage(4);
$post = array();
foreach($paginator as $post ) {
$post[] = $post;
}
$this->view->post = $paginator;
#TODO //add a check here for non-ajax requests (#improvment)
$this->view->posts = $paginator;
}
in one of the views (most probably in the pagination_cont.phtml) on the pagination controller add the ajax links
<?= $this->ajaxLink (
$this->url('cities'=>$this->page_num),array('id'=>'div_id','complete'=>'js_method(json_data)','method'=>post) ,array('format'=>'JSON'));
and add a JavaScript function of js_method(json_data) to modify the div with id = 'div_id' with a json data
function js_method(json_data) {
var content = parse.JSON(json_data);
$('#div_id').html('');
//fill it with the reposnse content some thing like $('#div_id').append(content);
}