CakePHP fails loading $ajax->form with Error 503 Service Unavailable - php

When I try to make an $ajax->form() call within my view, the server responds with: Error 503 Service Unavailable.
I have loaded:
App::Import('Ajax');
$ajax = new AjaxHelper();
(Within my view)
And then:
$ajax->form(array('type' => 'post',
array('type' => 'post',
'options' => array(
'model'=>'User',
'update'=>'dateTarget',
'url' => array(
'controller' => 'comments',
'action' => 'edit'
)
)
));
The only error I can seem to find is:
Undefined property: AjaxHelper::$Form
From within app/tmp/logs/debug.log
It should be noted that I tried echo'ing: get_class_methods($ajax) and it showed that form IS available.
Can someone advise me on how to proceed from here?
Thanks!

The AjaxHelper depends on the FormHelper (plus the HTMLHelper and JavascriptHelper). If you manually create an instance of the AjaxHelper you also have to create those dependencies (depending on the functionality you intend to use). It's done in the following way:
App::Import('Ajax');
$ajax = new AjaxHelper();
$ajax->Form = new FormHelper();
However, usually the helpers you want to use are added to the $helpers array of your controller(s):
public $helpers = array('Ajax');
See also http://book.cakephp.org/view/1096/Using-Helpers

Related

Yii Undefined yiiactiveform when not using clientValidation

I use Yii 1.1.14
I use form to capture an email, not using Yii ajaxValidation/clientValidation
<?php $form = $this->beginWidget('CActiveForm', array(
'id' => 'form-newsletter',
'action' => null,
'focus' => array($model, 'email'),
'htmlOptions' => array(
'role' => 'form',
),
)); ?>
I got this at js console
Uncaught TypeError: undefined is not a function
Which is refer to this
jQuery('#form-newsletter').yiiactiveform({'validateOnSubmit':true,'validateOnChange':true,'errorCssClass':'has-error has-feedback','successCssClass':'has-success has-feedback','inputContainer':'div.form-group','attributes':[{'id':'NewsletterForm_email','inputID':'NewsletterForm_email','errorID':'NewsletterForm_email_em_','model':'NewsletterForm','name':'email','enableAjaxValidation':true,'clientValidation':function(value, messages, attribute) {
I also check that jquery.yiiactiveform.js is present.
The question is, i dont want to use the default ajaxValidation/clientValidation, why is it loaded? and why it tells that yiiactiveform is undefined?
Thank you.
Check if you are including a newer version of jQuery than the one Yii includes (2.x for example) for the validation.
If you use other custom javascripts then must use in your layout code for example:
Yii::app()->clientScript->registerScriptFile(Yii::app()->request->baseUrl . '/js/bootstrap.min.js');

ZF2: How to get the route corresponding to the current url referrer?

I did not find any answer either from google nor from SO for my question, so I decided to ask.
Is there an easy way to get the params of the route corresponding to the current url's referrer ?
I am in the context of a controller action, so I have access to the $request and $response objects. I am actually retrieving the referrer using the following:
$referer = $request->getHeader('referer');
$refererUri = $referer->getUri();
What I do really want is to know if the url I got in the $refererUri variable matches a route which has a "connect" param defined as true, route being defined as the following:
'productAdd' => array(
'type' => 'literal',
'options' => array(
'route' => '/product/add',
'defaults' => array(
'controller' => 'Module\\Controller\\Product',
'action' => 'add',
'connect' => true
),
'spec' => '/add',
),
),
Right now I got in my $refererUri variable a URL like
http://local.example.com/dir/product/add
The solution I already thought about is to instanciate a request object from the URL and then to instanciate a route object from the request object, which will tell me if it matches. Then if I got a RouteMatch object in return, I will be able to get the value of the param I want.
But it really seems heavy for a pretty quick check, and it seems I cannot achieve that as a Route is not an object I can easily instantiate.
Any ideas ?
Edit: I found this post: which seems pretty close to what I asked for, but in the first answer proposed I cannot get where the $routeStack object is coming from. Any clues ?
I finally achieved my goal, so I am posting the answer for helping others in the same situation ;-)
What I did is basically :
Getting the referer URI:
$referer = $request->getHeader('referer');
$refererUri = $referer->getUri();
Instanciating a request from this URL:
$refererRequest = new Request();
$refererRequest->setUri($refererUri);
Get the router object:
$routeStack = $serviceManager->get('Router');
Find which route match the $refererRequest:
$match = $routeStack->match($refererRequest);
Check my parameter value from the RouteMatch object I got in return:
if ($match instanceof RouteMatch) {
$route = $match->getMatchedRouteName();
$connect = $match->getParam('connect');
}
And there it is ;-)

404 router in Lithium PHP

I know how to make response routes in the actual /config/routes.php file, but I can't find where to change the default 'fetal dispatcher' error. I'd like to be able to have it route to a nice 404 page I've made when there's a missing page/action controller. Is that possible?
Yes, you can take advantage of lithium\core\ErrorHandler for this. See the code in the default config/bootstrap/errors.php:
ErrorHandler::apply('lithium\action\Dispatcher::run', array(), function($info, $params) {
$response = new Response(array(
'request' => $params['request'],
'status' => $info['exception']->getCode()
));
Media::render($response, compact('info', 'params'), array(
'library' => true,
'controller' => '_errors',
'template' => 'development',
'layout' => 'error',
'request' => $params['request']
));
return $response;
});
This is saying, if any exception occurs during Dispatcher::run(), display the development.html.php template from the views/_errors folder with the layouts/error.html.php layout.
So you can change that -- maybe you check the Environment to see if this is a dev or production environment and display a different template for production.
Maybe if $info['exception']->getCode() === 404, you can switch to a template specifically for 404 errors.

Zend Framework 2 - Why i can't override MvcEvent's MatchRoute?

i would like to match all requests where user is unlogged to controller Admin\Controller\Sign and action in. I wrote this code in onBootstrap() method in Module.php file :
if (!$authService->hasIdentity()) {
$routeMatch = new RouteMatch(
array(
'controller' => 'Admin\Controller\Sign',
'action' => 'in'
)
);
$event->setRouteMatch($routeMatch);
}
I don't get any errors, but code doesn't work, why?
The problem here is that the application route event (MvcEvent::EVENT_ROUTE) is triggered after the (MvcEvent::EVENT_BOOTSTRAP).
Which means even if you're setting the route match at the bootstrap level, the application is going to override it with the route match of the request after the MvcEvent::EVENT_ROUTE.
If you want to avoid this overriding you need to add a listener for the route event with a very low priority to make sure it will not be overridden:
$e->getApplication()->getEventManager()->attach(MvcEvent::EVENT_ROUTE, array($this, 'onRouteEvent'), -1000000);
Note : the onRouteEvent would be the method of your Module class that handles the route event (similar to your code).
If you want to short-circuit your application running at the bootstrap level, what you can do is to send the headers with redirection code to the client:
//get the url of the login page (assuming it has route name 'login')
$url = $e->getRouter()->assemble(array(), array('name' => 'login'));
$response=$e->getResponse();
$response->getHeaders()->addHeaderLine('Location', $url);
$response->setStatusCode(302);
$response->sendHeaders();
add a route entry sign_in as below in the routes section of the module.config.php under admin module
'sign_in' => array(
'type' => 'Segment',
'options' => array(
'route' => '/admin/sign/in',
'defaults' => array(
'controller' => 'sign',
'action' => 'in',
),
),
),
and call the route in the controller like this
$this->redirect()->toRoute('sign_in');

Autoloading custom Zend_Form_Element

I can't get Zend to autoload a custom form element class. I did things exactly as Marcin describes here (except that my classes start with 'Zend' and not 'my' but I'm getting this error:
Warning: include_once(Zend\Form\Element\Div.php) [function.include-once]: failed to open stream: No such file or directory
I have Zend_Form_Element_Div inside forms\elements\ and Zend_View_Helper_FormDiv inside views\helpers\
Basically, every folder in the error message is missng an 's', the right path is Zend\Forms\Elements\Div.php
I also have this in my bootstrap, though I'm not sure if it's necessary, but I'm also using this for my forms and models folder (and some others, but I don't think there's need to post them all):
<?php
$resourceLoader->addResourceTypes(array(
'model' => array(
'namespace' => 'Model',
'path' => 'models'
),
'element' => array(
'namespace' => 'Element',
'path' => 'elements'
),
'form' => array(
'namespace' => 'Form',
'path' => 'forms'
)
));
?>
(Is there actually any other way of doing this autoloading? Instead of declaring every single folder?)
Update:
Element_Div in application/forms/elements/Div.php
In my forms init() method: $this->addElementPrefixPath('Element_', APPLICATION_PATH . '/forms/elements');
Error I'm getting: Fatal error: Class 'Element_Div' not found in C:\xampplite\htdocs\code\application\forms\PostForm.php on line 63
You essentially have to tell the form where to find custom elements by using:
$form->addElementPrefixPath()
In your case, you would use - either within the form's init() or __construct() method - something like:
$this->addElementPrefixPath('Zend_Form_Element_', APPLICATION_PATH . '/elements);;
However, I have agree with #Marcin. Naming your own classes with the Zend_ pseudo-namespace is ill-advised. Either:
Decide on an application namespace and declare it in your Bootstrap when you create your $resourceLoader
Create an custom library that resides on your include path - probably at the same level as the Zend library - and put your custom stuff out there.
Let me know if you need more details on either of these suggestions and I'll fatten up the explanations a bit.
Update based on comments
Using an empty appnamespace, your call to addElementPrefixPath() now changes to:
$this->addElementPrefixPath('Element_', APPLICATION_PATH . '/elements);
And I guess you could remove the elements entry from the $resourceLoader definition in your Bootstrap since it's really not doing anything.
Update 2
I assumed that you were adding the element to the form using the shortname, something like:
$form->addElement('div', 'my_div');
In this circumstance, we need to tell the $form and its plugin registry where to find an element of type 'div'. That's why we dealt with $form->addElementPrefixPath().
However, from the error message you are reporting, it appears that you are adding your custom element to the form using something like:
$div = new Element_Div();
$form->addElement($div, 'my_div');
In this case, it is not the $form and its plugin registry that has to worry about finding/loading/instantiating the custom element; it is the $autoloader via its $resourceLoader. In that case, there is no need for the $form->addElementPrefixPath(), which is essentially a hint to the form on how to find custom elements invoked by shortname.
What we need is to configure the $resourceLoader back in Bootstrap so it knows where to find the class. Assuming you stick with empty appnamespace (so your class is named Element_Div) and you place the file in application/forms/elements/Div.php, then the $resourceLoader call is as follows:
$resourceLoader->addResourceTypes(array(
'model' => array(
'namespace' => 'Model_',
'path' => 'models'
),
'element' => array(
'namespace' => 'Element_',
'path' => 'forms/elements'
),
'form' => array(
'namespace' => 'Form_',
'path' => 'forms'
)
));
That should do it. [Famous last words, eh?]
I prefer creating forms like this:
$form->addElement(new My_Form_Element_Whatever(array(
'name' => 'my_element',
'label' => 'My element',
)));
or
$form->addElement($whatever = new My_Form_Element_Whatever(array(
'name' => 'my_element',
'label' => 'My element',
)));
$whatever->removeDecorator('Errors');
when I need to further modify the element.

Categories