Zend Framework 1 pass parameters using get to the route - php

I hope the title does not sound too confusing, but I had no idea how to name my problem.
Brief intro:
I'm using Zend 1.1X.
At the moment I've been working with a search form sending few parameters via POST.
Now I have to change it to use GET, I have a route created looking similar to that:
"search/what/:what/shape/:shape"
and so on, I also have 2 optional parameters which takes null as default.
I'm trying to generate an URL (using Zend View Helper Url) at form's action, but it throws an exception:
Uncaught exception 'Zend_Controller_Router_Exception' with message what is not specified
I Now don't have idea what should I do. If I change my route to "search" only, it then sends the form correctly, but I end up with "search?what=XXXX&shape=YYYY" instead of "search/what/XXXX/shape/YYYY".
Is there any way that could be handled the way I like??? :>
#EDIT
I think this should also be mentioned - I have a different form, similar one, pointing to a route without parameters specified as well and the uri gets "translated" to the form of "key/value" pairs. The only difference between them is that the first one does not use Url helper, instead has the method part hard-coded and my form is being submitted programatically (button => jQuery stuff => submit). Would that make a difference here, as I believe it should not? :>
I hope any possible source of this behaviour will come up to you, because I'm really stuck at the moment and I simply can't find what's wrong..
Thanks in advance!

With the GET method a form generates an url like this: action?param1=val1&param2=val2&....
I see two solutions:
The first is to regenerate the URL by javacsript, we can imagine something like this:
<form method="get" id="id_form">
....
</form>
<script>
var objet_form = document.getElementById('id_form');
function gestionclic(event){
var url = objet_form.action;
for(var i = 0; i < objet_form.length; i++){
url += "/" + objet_form[i].name + "/" + objet_form[i].value;
}
objet_form.action = url;
}
if (objet_form.addEventListener){
objet_form.addEventListener("submit", gestionclic, false);
} else{
objet_form.attachEvent("onsubmit", gestionclic, false);
}
</script>
But I don't think this is a good solution.
The second is to manage it with a plugin:
For the plugin, it must be declared in the bootstrap.
For example:
public function _initPlugins(){
$front = Zend_Controller_Front::getInstance();
$front->registerPlugin(new Application_Plugin_PRoutage());
}
with this example, the application/plugins folder, create the PRoutage.php plugin like this:
class Application_Plugin_PRoutage extends Zend_Controller_Plugin_Abstract
{
public function dispatchLoopStartup(Zend_Controller_Request_Abstract $request)
{
...
}
}
and with the variable $request you have access to your data as an array with $request->getParams().
We can imagine something like this:
public function dispatchLoopStartup(Zend_Controller_Request_Abstract $request)
{
$param = $request->getParams();
$what = "";
$shape = "";
if (isset($param['what']) $what = $param['what'];
if (isset($param['shape']) $shape = $param['shape'];
if ($what == "XXXX" && $shape == "YYYY"){
$request->setControllerName('other_controler')
->setActionName('other_action')
->setDispatched(true) ;
}
}
I hope it will help you

Related

Get the form name of Facebook lead ads using webhook

I have two different Facebook leads ad campaigns (A and B) connected to the same F.B page, I've connected it to a webhook following this guide using Facebook ads PHP sdk, and pass the leads to my C.R.M, everything works fine, the problem is that I can't tell if the lead came from form A or B.
I've tried to pull the from name like this:
$input = json_decode(file_get_contents('php://input'), true);
if($input)
{
$form_id = $input['entry'][0]['changes'][0]['value']['form_id'];
$form = AdsWebhookHandler::getFormName($form_id);
}
From the AdsWebhookHandlerclass:
public static function getFormName($form_id)
{
$form = new LeadgenForm($form_id);
if(!$form) return $form_id;
return $form->read();
}
But the form always returns empty ({}) for some reason.
Does anybody know how can I pull the form name? or even better - is it possible to pass custom hidden fields in the form?
Thank you all for an answer :)
O.K so I figure out how to get the form name, all I needed to do is use the getData() function included in the Facebook PHP SDK, my code looks like this now:
public function getFormName($form_id)
{
$form = new LeadgenForm($form_id,null,$this->fb_instance);
if(!$form) return $form_id;
$data = $form->read()->getData();
return isset($data['name']) ? $data['name'] : $form_id;
}
Hope it'll help someone in the future :)

Gii model generation not getting past first step - strange bevavior, what's causing this?

I've installed the latest version of yii2 using the advanced template. The website is working fine. For some reason the Gii generation tool is stuck and does not react as expected after clicking the preview button. Instead of showing a new form with the "Generate" button, it shows the same form unchanged without any messages as to what is happening.
Using xdebug I can see in the "actionView" method of the DefaultController that the array value $_POST['preview'] is not set, i.e. it doesn't exist in the $_POST array. I have not changed anything in the Form of the view and everything looks OK. The submit button has the name "preview" and the form is submitted but the $_POST array is not being filled with the value of the submit button. Therefore the controller does not proceed with the next steps of the generation process.
public function actionView($id)
{
$generator = $this->loadGenerator($id);
$params = ['generator' => $generator, 'id' => $id];
// ###############################################################################
// ### THIS IF STATEMENT IS NOT TRUE BECAUSE $_POST['preview'] IS NOT SET !!! ###
// ###############################################################################
if (isset($_POST['preview']) || isset($_POST['generate'])) {
// ###############################################################################
if ($generator->validate()) {
$generator->saveStickyAttributes();
$files = $generator->generate();
if (isset($_POST['generate']) && !empty($_POST['answers'])) {
$params['hasError'] = !$generator->save($files, (array) $_POST['answers'], $results);
$params['results'] = $results;
} else {
$params['files'] = $files;
$params['answers'] = isset($_POST['answers']) ? $_POST['answers'] : null;
}
}
}
return $this->render('view', $params);
}
Does anyone have an idea what could be causing this? I have a hunch that it is something quite simple that I'm overlooking, but I've never had a situation where POST variable from a Form are not being sent to the server.
False Alarm. I've found the problem. The Gii view was creating the HTML Form incorrectly.

How can I use ajax in Zend Framework 2?

I am trying a small ajax application whereby I only want to return a hello world string from my controller action.
it is returning the Hello world but along with this, it is also returning my template file..
I tried to disable it the templating using the following code in the action of my controlelr
$this->_helper->layout()->disableLayout();
$this->_helper->viewRenderer->setNoRender( true );
but this returns me this error
SCREAM: Error suppression ignored for
( ! ) Notice: Undefined property: Survey\Controller\SurveyController::$_helper in C:\wamp\www\zend\module\Survey\src\Survey\Controller\SurveyController.php on line 55
SCREAM: Error suppression ignored for
( ! ) Fatal error: Call to a member function layout() on a non-object in C:\wamp\www\zend\module\Survey\src\Survey\Controller\SurveyController.php on line 55
Call Stack
How do I fix this ?
EDIT
I modifed the controller such that it looks like this
public function registerAction()
{
$result = new JsonModel(array(
'some_parameter' => 'some value',
'success'=>true,
));
return( $result );
}
Added strategies in the module..module.config in module appl directory
'strategies' => array(
'ViewJsonStrategy',
),
Still, in the ajax response I get the template being returned
Here's a solid example:
http://akrabat.com/zend-framework-2/returning-json-from-a-zf2-controller-action/
You should be using JsonMoodels to send back a Json Response.
i use this in my controller:
$view = new ViewModel(array('form'=>$my_form));
//disable layout if request by ajax
$view->setTerminal($request->isXmlHttpRequest());
$view->setTemplate('path/to/phtml');
return $view;
The user wanted to know how to get just the html back, not json as Andrews reply offers.
I also wanted the html returned so i could use it with jquery qtip plugin and this is how i did it.
I also had to make the page degrade gracefully in case javascript failed, e.g. the page output should render properly in the layout template.
/**
* Tourist Summary action
*
* #return ViewModel
*/
public function touristSummaryAction()
{
// Get the Id
$id = $this->params()->fromRoute('id', '');
// Get the data from somewhere
$data = array() ;
// Get the html from the phtml
$view = new ViewModel(
array(
'id' => $id ,
'data' => $data ,
)
);
//disable layout if request by ajax
$view->setTerminal($this->getRequest()->isXmlHttpRequest());
return $view;
}
The most simple way to send ajax requests and handle responses is the zf2 module WasabiLib https://github.com/WasabiLib/wasabilib_zf2_skeleton_application
You only need to add "ajax_element" to the class-attribute to the element which you want to cause the ajax request. It does not matter if it is a form submit or a link or a button. Visit the examples page http://www.wasabilib.org/application/pages/examples
If your application does a lot of ajax I recommend this module.
Take a look at this module. www.wasabilib.org
Seems that you it manages ajax very well.
If you do not have a application you can use the Wasabilib Skeleton https://github.com/WasabiLib/wasabilib_zf2_skeleton_application. It comes with all necessary assets in the right place.
If you already have an application you should clone the module: https://github.com/WasabiLib/wasabilib
Minimal requirements: jQuery, ZF2
Add the module to application.config.php.
Include the wasabilib.min.js after jquery in the head of your layout.phtml
How it works
in your .phtml-file you have a form like this:
<form id="simpleForm" class="ajax_element" action="simpleFormExample" method="POST">
<input type="text" name="written_text">
<input type="submit" value="try it">
</form>
Anywhere else in your phtml you can place an element where the response is shown.
In your Controller the following method:
public function simpleFormExampleAction(){
$postArray = $this->getRequest()->getPost();
$input = $postArray['written_text'];
$response = new Response(new InnerHtml("#element_simple_form","Server Response: ".$input));
return $this->getResponse()->setContent($response);
}
The form has a class "ajax_element" this will say the the library that the request will be done with an xmlhttp-request. It wont work if you do not give an id to the requesting element. So the form has the ID "simpleForm". The action is the "path/to/controller" just like a normal request.
In the controller action a new WasabiLib\Ajax\Response object is instanciated.
The InnerHtml class is for replace, prepend and append html or normal text to a selector.
In this case the selector is an ID "element_simple_form". The first parameter of the InnerHtml class is the selector. Make sure that you write #yourElementId or .yourClassSelector. For IDs an "#" and for class selectors "."
The second parameter is the Text you want to fill in this element.
The response object can handle a lot more responses which you can add with
$response->add($anotherResponseType);
A list of possible response types is here: http://www.wasabilib.org/application/pages/components
The module is build to handle ajax request an responses in a very simple way. Once you have understood the behavior you can handle almost every practical ajax need.
This works for me:
public function ajaxAction(){
$data = array(
'var1' => 'var1Value',
'var2' => 'var2Value',
);
$response = $this->getResponse();
$response->setStatusCode(200);
$response->setContent(json_encode($data));
$headers = $response->getHeaders();
$headers->addHeaderLine('Content-Type', 'application/json');
return $response;
}
Output:
{"var1":"var1Value","var2":"var2Value"}

How to remove action part in zend framework URLs

I`m using zend framework and my urls are like this :
http://target.net/reward/index/year/2012/month/11
the url shows that I'm in reward controller and in index action.The rest is my parameters.The problem is that I'm using index action in whole program and I want to remove that part from URL to make it sth like this :
http://target.net/reward/year/2012/month/11
But the year part is mistaken with action part.Is there any way ?!!!
Thanks in advance
Have a look at routes. With routes, you can redirect any URL-format to the controller/action you specify. For example, in a .ini config file, this will do what you want:
routes.myroute.route = "reward/year/:myyear/month/:mymonth"
routes.myroute.defaults.controller = reward
routes.myroute.defaults.action = index
routes.myroute.defaults.myyear = 2012
routes.myroute.defaults.mymonth = 11
routes.myroute.reqs.myyear = "\d+"
routes.myroute.reqs.mymonth = "\d+"
First you define the format the URL should match. Words starting with a colon : are variables. After that you define the defaults and any requirements on the parameters.
you can use controller_plugin to control url .
as you want create a plugin file (/library/plugins/controllers/myplugin.php).
then with preDispatch() method you can get requested url elements and then customize that for your controllers .
myplugin.php
class plugins_controllers_pages extends Zend_Controller_Plugin_Abstract
{
public function preDispatch(Zend_Controller_Request_Abstract $request)
{
$int = 0;
$params = $this->getRequest()->getParams();
if($params['action'] != 'index' ) AND !$int)
{
$int++;
$request->setControllerName($params['controller']);
$request->setActionName('index');
$request->setParams(array('parameter' => $params['action']));
$this->postDispatch($request);
}
}
}

How to add extra parameter in zend paging

How i can add extra parameter in the zend paging.I have to provide filter functionality in the listing user. so i want to send search keywords with page numbers.
Paging code
$page = $this->_getParam('page', 1);
$paginator = Zend_Paginator::factory($data);
$paginator->setItemCountPerPage(2);//PAGING_RESULT_PER_PAGE
$paginator->setCurrentPageNumber($page);
$paginator->setPageRange(PAGING_PAGES_RANGE_PER_PAGE);
$this->view->users = $paginator;
I want to add search data onchange event to the paging .
This paging is working using ajax now what i want to it should be changed as per the filter data. I am not able to perform this....can you please provlde me any suggestion please
You can change the code from the javascript.
<script>
$(document).ready(function(){
$('.paginationControl a').click(function(){
if($('#keyword').val() != '')
{
var href = $(this).attr('href')+'/keyword/'+$('#keyword').val();
$(this).attr('href', href);
}
});
});
</script>
<input type="text" name="keyword" value="" id="keyword"/>
<div class="paginationControl">
2
3
4
5
</div>
I'm not quite sure what you mean with "extra parameter in the zend paging" ... are you trying to pass a GET-Parameter to an controller which has an paginator? What is inside $data? How does your search parameter and your route look like? You might try the following inside your bootstrap.php (if passing a get var is what you're struggling with):
protected function _initConstants()
{
[...]
defined('QSA_SEARCH') || define('QSA_SEARCH', 'q');
[...]
}
And inside your controller you can access it via:
[...]
$search = $this->getRequest()->getParam(QSA_SEARCH);
[...]
Passing a search string via get request:
http://domain.com/<controller>/<pagenum>?q=<searchstring>
e.g.:
http://domain.com/users/2?q=foo
EDIT:
Or are you having problems passing the search string towards Zend_Paginator::factory?

Categories