php, how to send a manual post within the zend framework? - php

im not sure if the question was framed correctly, but here is my situation:
i have two actions: indexAction and searchAction
a third action looks something like this:
public function customsearchAction()
{
$request = $this->getRequest();
if($request->isPost()){
$category = $request->getParam('select_category');
$searchString = $request->getParam('header_search_form');
if($category == 'index'){
$this->_redirector->gotoSimple('index', 'index', null,
array('term' => $searchString )
);
}
if($category == 'search'){
$this->_redirector->gotoSimple('search', 'index', null,
array('term' => $searchString )
);
}
}
}
this is fine and dandy, the only problem is that the redirect adds the term as a get string instead of a post like i need it.
any ideas?

Browser redirect will always add term to GET for next request to process. What you can do here is use ZF MVC internal redirect using 'forward' .
$this->_forward('search','index',null,array('term' => $searchString ));
Inside your searchAction
$searchString = $this->_getParam('term');

Related

how to redirect to the same page after editing data?

sensei. can you help me with my code? i wan to redirect page to the same page after edit it.
here is my controller
function edit_book(){
$editBook = array(
'id' => $this->input->post('id'),
'book_title' => $this->input->post('book_title'),
'category' => $this->input->post('category'),
'author' => $this->input->post('author')
):
$this->m_profile->edit_book($data1, $data, 'book_data');
redirect('app/book')
}
suppose im editing the data from page number 3. how can i redirect to page 3 (app/book/3) again after submit the edited data?
i have try to solve it by get URI value(suppose the page is app/book/3)<-- i need this '3'to put in redirect code. so i implement this code from many stackeroverflow answer, hope to get some array i can use
$url = "//{$_SERVER['HTTP_HOST']}{$_SERVER['REQUEST_URI']}";
$escaped_url = htmlspecialchars( $url, ENT_QUOTES, 'UTF-8' );
$query_str = parse_url($escaped_url, PHP_URL_QUERY);
parse_str($query_str, $query_params);
print_r($query_params);
but it results array()or null. anyone can help me. thanks
function edit_book(){
$id = $this->input->post('id');
$editBook = array(
'id' => $this->input->post('id'),
'book_title' => $this->input->post('book_title'),
'category' => $this->input->post('category'),
'author' => $this->input->post('author')
):
$this->m_profile->edit_book($data1, $data, 'book_data');
$url = base_url('app/book/'.$id);
redirect( $url)
}
function book($id = NULL)
{
//get record using $id;
}
try below code me be solve u r issue. i have pass id in url.
In the controller need to pass the last value like "3" as argument so that any edited value can be pass to the controller. And then after editing the code you can redirect by the php header function with the passed value as argument to redirect on the same page like this example:
<?php
function edit_book($id){
Your all edited codes here.
// To redirect to the same page with avalue
redirect('same_controller/method/'.$id, 'refresh');
}
?>

Cakephp routing controller alias

I'm trying to do the same as this site, stackoverflow, do with their URLs.
CakePHP works like this: website/controller/action/
I want to config routing to achieve this:
myWebSite.com/questions/(question_id)/(question)/
eg: myWebSite.com/questions/12874722/cakephp-routing-controller-alias /
I didnt figured it out how to do this bold part of URL.
In your Config/routes.php
Router::connect('/questions/*', array('controller' => 'questions', 'action' => 'view'));
In Controller/QuestionsController.php
view action get question id as
public function view() {
$question_id = isset($this->request->params['pass'][0]) ? $this->request->params['pass'][0] : "";
$question = isset($this->request->params['pass'][1]) ? $this->request->params['pass'][1] : "";
if( empty($question_id) ) {
throw new NotFoundException('Could not find that question');
}
// if $question is empty then get slug from database and redirect to /question_id/question
// Get question details and set
}

Saving data on GET request in CakePHP

I am building a simple mechanism where a user can like a post by clicking on a link. I'm using GET rather than POST as I want to allow the method to fire via the URL.
That been said how do I save data using GET? As the request data doesn't exist in this scenario... My model looks like:
class Like extends AppModel
{
public $name = 'Like';
public $belongsTo = array('User','Post');
}
and the method for adding looks like:
public function add( $id )
{
$post = $this->Post->find('first', array(
'conditions' => array('Post.id'=>Tiny::reverseTiny($id))
));
if (!$post)
{
throw new NotFoundException('404');
}
if($post['Post']['user_id'] == $this->Auth->user('id'))
{
$this->Session->setFlash('You can\'t like your own post... That\'s just silly!');
}
if ($this->Like->create())
{
$liked = $this->Like->find('first', array(
'conditions' => array('Like.id'=>Tiny::reverseTiny($id), 'Like.user_id'=>$this->Auth->user('id') )
));
if(!$liked){
$this->Like->saveField('user_id', $this->Auth->user('id'));
$this->Like->saveField('post_id', $post['Post']['id']);
$this->redirect(array('controller'=>'posts','action'=>'view','id'=>Tiny::toTiny($post['Post']['id']),'slug'=>$post['Post']['slug']));
} else {
$this->Session->setFlash('You already like this post!');
}
else
{
$this->Session->setFlash('Server broke!');
}
}
Can anyone help?
<?php echo $this->Html->link('1', array('controller'=>'followers','action'=>'add','id'=>Tiny::toTiny($post['Post']['id'])),
array('title'=>'Follow','class'=>'follow')); ?>
This part all works fine. It's saving a new row in the DB on GET that I'm struggling with.
Hi you just need to make a link to your controller action and pass you variable in the url.
to be clear the link on the post to like is in your post view :
$this->Html->link('like this post', array('controller' => 'like', 'action' => 'add', $postId))
It should render a link like this :
www.yourWebSite/likes/add/1 to like the postId 1,
variables after your action (add) are interpreted as variable for your controller action
if your fonction add had been
public function add($postId, $wathever){
}
the url should look like www.yourWebSite/likes/add/1/blabla
where 1 is the first var for the add action and blabla the second one and so on.
this is the equivalent of a non rewriting url : ?postId=1&whatever=blabla
EDIT :
if(!$liked){
//simulate the post behaviour
$this->request->data['Like']['user_id'] = $this->Auth->user('id');
$this->request->data['Like']['post_id'] = $post['Post']['id'];
//save the data
if ($this->Like->save($this->request->data)) {
$this->Session->setFlash(__('Thanks for your support !'));
$this->redirect(array('controller'=>'posts','action'=>'view','id'=>Tiny::toTiny($post['Post']['id']),'slug'=>$post['Post']['slug']));
} else {
$this->Session->setFlash('Server broke!');
}
}
How about using save with id=0 instead of create?
<?php
$like = array(
"Like" => array
(
"id" => 0,
"user_id" => $this->Auth->user("id"),
"post_id" => $post['Post']['id']
)
);
$result = $this->Like->save($like);
if(!$result){$this->Session->setFlash('Server broke!');}
$this->redirect(array('controller'=>'posts','action'=>'view','id'=>Tiny::toTiny($post['Post']['id']),'slug'=>$post['Post']['slug']));
?>

CakePHP: Pagination in an Element on home.ctp

I'm using CakePHP to create a frontend UI for PowerDNS, using a MySQL backend. On the front page of the app I want to have a handful of widgets ('Quickly add a record', 'Quickly add a domain' etc.). One of the widgets I want is a paginated list of existing domains.
The index function in DomainsController.php looks like this:
public $paginate = array(
'fields' => array('id', 'name'),
'limit' => 25,
'order' => array( 'name' => 'asc' ),
'conditions' => array( "NOT" => array( "name LIKE" => "%.arpa" ) )
);
public function index() {
$domains = $this->paginate();
if ( $this->request->is('requested')) {
return $domains;
} else {
$this->set('domains', $domains);
}
}
I've created an element that looks like this:
<?php $domains = $this->requestAction('Domains/index'); ?>
<ol>
<?php foreach( $domains as $domain) :?>
<li>echo $domains['domain']['name']</li>
<?php endforeach; ?>
</ol>
<?php echo $paginator->numbers(); ?>
When I visit the front page, I get an 'Undefinied variable: paginator' error. I've tried using $this->Paginator->numbers() instead but that just gives me 'Undefined property: View::$Paginator'. Adding the 'Paginator' helper to PagesController.php doesn't help either - $this->Paginator becomes available but I get 'Undefined index: pageCount'.
Is it possible to do this kind of pagination from an element on home.ctp or am I going to have to do some custom JavaScript stuff?
EDIT
Now I'm getting somewhere: I changed my DomainsController index function to this:
public function index() {
$domains = $this->paginate();
$paginator = $this->params;
if ( $this->request->is('requested')) {
return compact( 'domains', 'paginator' );
} else {
$this->set('domains', $domains);
}
}
And added the following to the domainList.ctp element:
<?php
$result = $this->requestAction('Domains/index');
$domains = $result['domains'];
$this->Paginator->request = $result['paginator'];
?>
<ol>
<?php foreach( $domains as $domain) :?>
<li>echo $domains['domain']['name']</li>
<?php endforeach; ?>
</ol>
<?php echo $paginator->numbers(); ?>
$this->Paginator is now working properly and I can access all of its methods and properties and so on as normal. My problem now is that if I click on, say, '2', the browser navigates to /pages/home/page:2 but the domain list still shows page 1. Just need to figure out how to pass 'page:2' to the element. And AJAX-ify the whole thing so that I don't need to refresh the whole page.
Firstly, don't do this:
$domains = $this->requestAction('Domains/index');
It's expensive and not good practice and I'm not sure why you need to be doing it from your example.
Secondly, call your paginate like this:
$domains = $this->Paginate('Domain');
OK, I solved this problem, although my solution probably isn't very elegant.
DomainsController.php has a listDomains() function that looks like this:
public function listDomains() {
$domains = $this->paginate();
$paginator = $this->params;
if ( $this->request->is('ajax') ) {
$this->set( 'domains', $domains );
}
if ( $this->request->is('requested')) {
return array( 'domains' => $domains, 'paginator' => $paginator, 'paging' => $this->params['paging'] );
} else {
$this->set( 'domains', $domains );
}
}
home.ctp references an element called domainList.ctp. domainList.ctp, below, in turn uses requestAction() - I know, I know - to call the domainList() function above. Bequest the request is requested, an array containing the values of $domains and $paginator is sent back to the element.
domainList.ctp contains this code:
<?php
$result = $this->requestAction('Domains/listDomains', array('updateId' => 'domainList') );
$domains = $result['domains'];
$paginator = $result['paginator'];
$this->Paginator->request = $paginator;
$this->Paginator->options(array(
'update' => '#domainList',
'evalScripts' => true,
'url' => array('controller' => 'Domains', 'action' => 'listDomains', 'updateId' => 'domainList' ),
));
?>
Essentially what I'm doing here is manually re-populating $this->Paginator->request with the params that were originally sent to the DomainController's domainList() function. This lets me access the various paginator functions, like numbers(), prev() and next(), properly. It's a bit messy but guess what? It gets a little messier.
When you click on the links created by those paginator functions, the 'if ( $this->request->is('ajax') )' segment is executed and the div object on the page is updated with the contents of View/Domains/domainList.ctp instead of View/Elements/domainList.ctp. The contents of View/Domains/domainList.ctp is more or less the same as the corresponding element and the two have to be kep more or less syncronised. The difference is that we don't need to manually populate $this->Paginator:
<?php
$this->Paginator->options(array(
'update' => '#domainList',
'evalScripts' => true,
'url' => array('controller' => 'Domains', 'action' => 'listDomains', 'updateId' => 'domainList' ),
));
?>
Like I said, it's messy and inelegant but it worked for me. I'd be happy to know if anyone has a less kludgy way to do this.

symfony link to change language and stay on the page

I would like to make a link the will be in the layout to change the language. So it should work for many routes.
for example
i'm on the page /en/myModule
and the links should point to
/de/myModule
/fr/myModule
I found a solution here :http://oldforum.symfony-project.org/index.php/m/70452/
<?php echo link_to(
'Germany',
'#default?' . http_build_query(array(
'sf_culture' => 'de',
'module' => $sf_request->getParameter('module'),
'action' => $sf_request->getParameter('action'))
), null, '&')) ?>
Problem is that I need a default route, and I don't want to have it.
Is there any solution for what I need ?
routing:
user_switch_culture:
url: /culture-change/:language
param: { module: user, changeCulture }
In your layout template:
<?php echo link_to(image_tag("flags/gb.gif"), "user_switch_culture", array("language"=>"en", "redirect"=>$sf_request->getUri())) ?>
Link will generate:
http://example.com/culture-change/fr?redirect=http//example.com/fr/control-panel
In your action:
public function executeChangeCulture(sfWebRequest $request)
{
$oldCulture = $this->getUser()->getCulture();
$newCulture = $request->getParameter("language");
$this->getUser()->setCulture($newCulture);
return $this->redirect(str_replace('/'.$oldCulture.'/', '/'.$newCulture.'/', $request->getParameter("redirect")));
}
Just off the top off my head. should work...
Not great: Should do some filter on the redirect to make sure it's the correct domain name etc.
Why not make a specific action for this?
public function executeChangeLanguage(sfWebRequest $request)
{
if (in_array($request->getParameter('lang'), sfConfig::get('app_site_languages'))
{
$this->getUser()->setCulture($request->getParameter('lang'));
}
// you can ask the browser for referrer or send a parameter to the change language action
// something like '/change-language?lang=ro&redirect=your page'.
// if you are sending a redirect parameter you must make sure that it's actually a page within your site
$referrer = $request->getReferer();
// or $referrer = $request->getParameter('redirect');
// you can further check the referrer here
return $this->redirect($referrer);
}
I think that I have a solution:
$uri = sfContext::getInstance()->getRouting()->getCurrentRouteName();
echo link_to('French', $uri, array('sf_culture'=>'fr')) . ' | ';
echo link_to('English', $uri, array('sf_culture'=>'en')) . ' | ';
echo link_to('German', $uri, array('sf_culture'=>'de'));
Is it a good one or is there a better solution ?

Categories