Here's my code so far:
public function actionDelete($id) {
$jenis = Usaha::model()->findByAttributes(array('id_jenis' => $id));
if($jenis==''){
$this->loadModel($id)->delete();
}
else {
throw new CHttpException(400, "data tidak bisa di hapus karena berhubungan dengan data yang lain");
}
// if AJAX request (triggered by deletion via admin grid view),
// we should not redirect the browser
if (!isset($_GET['ajax']))
$this->redirect(isset($_POST['returnUrl']) ? $_POST['returnUrl'] : array('admin'));
}
}
Can i get some alert another exception 404, or can i customize my alert?
You can customize the exception yes.
http://www.yiiframework.com/doc/api/1.1/CHttpException
And here for the codes:
http://www.yiiframework.com/doc/api/1.1/CHttpException#statusCode-detail
Related
I am making a module and I need to make an ajax request, with JSON response if possible, how can i do this ?
I don't understand really well the structure of Prestashop 1.7 on this.
Thanks !
This is pretty simple, you just have to make the controller with Prestashop's standards then link it to your frontend Javascript.
Name a php file like this : ./modules/modulename/controllers/front/ajax.php
Then put inside :
<?php
// Edit name and class according to your files, keep camelcase for class name.
require_once _PS_MODULE_DIR_.'modulename/modulename.php';
class ModuleNameAjaxModuleFrontController extends ModuleFrontController
{
public function initContent()
{
$module = new ModuleName;
// You may should do some security work here, like checking an hash from your module
if (Tools::isSubmit('action')) {
// Usefull vars derivated from getContext
$context = Context::getContext();
$cart = $context->cart;
$cookie = $context->cookie;
$customer = $context->customer;
$id_lang = $cookie->id_lang;
// Default response with translation from the module
$response = array('status' => false, "message" => $module->l('Nothing here.'));
switch (Tools::getValue('action')) {
case 'action_name':
// Edit default response and do some work here
$response = array('status' => true, "message" => $module->l('It works !'));
break;
default:
break;
}
}
// Classic json response
$json = Tools::jsonEncode($response);
echo $json;
die;
// For displaying like any other use this method to assign and display your template placed in modules/modulename/views/template/front/...
// Just put some vars in your template
// $this->context->smarty->assign(array('var1'=>'value1'));
// $this->setTemplate('template.tpl');
// For sending a template in ajax use this method
// $this->context->smarty->fetch('template.tpl');
}
}
?>
In your Module Hooks, you need to bring access to the route in JS, so we basicaly make a variable :
// In your module PHP
public function hookFooter($params)
{
// Create a link with the good path
$link = new Link;
$parameters = array("action" => "action_name");
$ajax_link = $link->getModuleLink('modulename','controller', $parameters);
Media::addJsDef(array(
"ajax_link" => $ajax_link
));
}
On the frontend side, you just call it like this in a JS file (with jQuery here) :
// ajax_link has been set in hookfooter, this is the best way to do it
$(document).ready(function(){
$.getJSON(ajax_link, {parameter1 : "value"}, function(data) {
if(typeof data.status !== "undefined") {
// Use your new datas here
console.log(data);
}
});
});
And voila, you have your ajax ready to use controller
I'm currently writing functionnal tests for my symfony app. I use symfony 3 (3.1.6) with phpunit 5.6.1.
Edit : As requested by Alvin Bunk, my app is not a website, it is an API that returns only JSON. As i added in the two updates below, the Symfony test client sends a proper request object with the form data but the controller of the app receives an empty object.
Here is the code i use to test my form :
public function testSaveMediaFromMediaUrl()
{
$client = static::createClient();
$crawler = $client->request('GET', '/form');
$form = $crawler->selectButton('OK')->form();
$form['mediaUrl'] = 'http://example.com';
$client->submit($form);
var_dump($client->getResponse()->getContent());
}
The correct action of my controller is called but there is nothing in the request object when the action is called from the tests suite. using a regular web browser, everything works fine. In the controller, I use $request = Request::createFromGlobals(); to create the request object
I also tried this code to post the data and I get the same result : no POST data is received in the controller.
direct post request without using the form
public function testSaveMediaFromMediaUrl()
{
$client = static::createClient();
$crawler = $client->request('POST', '/media', ['mediaUrl' => 'http://example.com']);
var_dump($crawler->html());
}
adding the data in the submit method
public function testSaveMediaFromMediaUrl()
{
$client = static::createClient();
$crawler = $client->request('GET', '/form');
$form = $crawler->selectButton('OK')->form();
$client->submit($form, ['mediaUrl' => 'http://example.com']);
var_dump($client->getResponse()->getContent());
}
Is there something I'm doing wrong ?
EDIT:
Here is the dump of the request object I get in the controller action.
.object(Symfony\Component\HttpFoundation\Request)#1047 (21) {
["attributes"]=>
object(Symfony\Component\HttpFoundation\ParameterBag)#1050 (1) {
["parameters":protected]=>
array(0) {
}
}
["request"]=>
object(Symfony\Component\HttpFoundation\ParameterBag)#1048 (1) {
["parameters":protected]=>
array(0) {
}
}
["query"]=>
object(Symfony\Component\HttpFoundation\ParameterBag)#1049 (1) {
["parameters":protected]=>
array(0) {
}
}
["server"]=>
object(Symfony\Component\HttpFoundation\ServerBag)#1053 (1) {
["parameters":protected]=>
array(35) {[...]}
}
["files"]=>
object(Symfony\Component\HttpFoundation\FileBag)#1052 (1) {
["parameters":protected]=>
array(0) {
}
}
["cookies"]=>
object(Symfony\Component\HttpFoundation\ParameterBag)#1051 (1) {
["parameters":protected]=>
array(0) {
}
}
["headers"]=>
object(Symfony\Component\HttpFoundation\HeaderBag)#1054 (2) {
["headers":protected]=>
array(0) {
}
["cacheControl":protected]=>
array(0) {
}
}
["content":protected]=>
NULL
["languages":protected]=>
NULL
["charsets":protected]=>
NULL
["encodings":protected]=>
NULL
["acceptableContentTypes":protected]=>
NULL
["pathInfo":protected]=>
NULL
["requestUri":protected]=>
NULL
["baseUrl":protected]=>
NULL
["basePath":protected]=>
NULL
["method":protected]=>
NULL
["format":protected]=>
NULL
["session":protected]=>
NULL
["locale":protected]=>
NULL
["defaultLocale":protected]=>
string(2) "en"
}
Edit-2:
Here is the dump of the request object sent by the client (in the test case : var_dump($client->getRequest()->request);) :
object(Symfony\Component\HttpFoundation\ParameterBag)#753 (1) {
["parameters":protected]=>
array(4) {
["mediaUrl"]=>
string(41) "http://example.com"
["url"]=>
string(0) ""
["token"]=>
string(0) ""
["sizes"]=>
string(0) ""
}
}
The "test browser" seems sends the form data to the app...
Problem solved :
In my controller, I used $request = Request::createFromGlobals() as written in the doc. I removed this line and added $request as a parameter of the controller action and now the request contains the POST data sent by the test client.
My action is now defined like this :
public function generateAction(Request $request) {
// no more $request = Request::createFromGlobals();
$request->request->get('mediaUrl'); // contains data
}
usually a post request to a form return a redirect, if so check that the redirect is the correct response and follow the redirection, as example:
$client->submit($form);
$this->assertTrue($client->getResponse()->isRedirect());
$this->crawler = $client->followRedirect();
Hope this help
EDIT:
Another way could be:
$form = $crawler->selectButton('OK')->form(array(
'mediaUrl' => 'http://example.com')
);
$client->submit($form);
I'm trying to get work with social authentication using liknedin provider in Laravel 5.1 but it's giving me that exception.
I have implemented such authentication using "github" and "google" providers,but this one sounds weird regarding linkedin provider is built-in in Laravel 5.1
This is my redirect function
public function redirectToProvider($provider)
{
return Socialite::driver($provider)->redirect();
}
and my setting
'linkedin' => [
'client_id' =>env('LinkedIn_APP_ID'),
'client_secret' => env('LinkedIn_APP_SECRET'),
'redirect' => 'http://localhost:88/laravel/public/social/login/linkedin',
]
Have you registered your redirect URL in your LinkedIn application's configuration (https://www.linkedin.com/developer/apps)?
public function redirectToProvider()
{
return Socialite::driver('linkedin')->redirect();
}
public function handleProviderCallback(Request $request)
{
try
{
$provider_user = Socialite::driver('linkedin')->user();
}
catch ( Exception $e )
{
$request->session()->flash( 'alert-danger', 'Invalid request data detected! please try again.' );
return redirect( '/' );
}
dd($provider_user);
}
Is it possible to redirect to a route in Layout.phtml in ZF2. I want to redirect to login page if the user is not logged in from layout.phtml
So far i have tried:
<?php $auth = new AuthenticationService();
if ($auth->hasIdentity()) {?>
<li class="active"><a href="<?php echo $this->url('home') ?>">
<?php echo $this->translate('Home') ?></a></li>
<li class="active"><?php echo $this->translate('Logout') ?></li>
<?php
}
else
{
$this->_forward('login/process');
} ?>
its giving me error "get was unable to fetch or create an instance for _forward"
BOOTSTRAP CODE:
public function onBootstrap(MvcEvent $e)
{
$e->getApplication()->getServiceManager()->get('translator');
$eventManager = $e->getApplication()->getEventManager();
$moduleRouteListener = new ModuleRouteListener();
$moduleRouteListener->attach($eventManager);
$eventManager = $e->getApplication()->getEventManager();
//nothing's available for non logged user, so redirect him to login page
$eventManager->attach("dispatch", function($e) {
$match = $e->getRouteMatch();
$list = $this->whitelist;
// Route is whitelisted
$name = $match->getMatchedRouteName();
if (in_array($name, $list)) {
return;
}
$sm = $e->getApplication()->getServiceManager();
$controller = $e->getTarget();
$auth = $sm->get('AuthService');
if (!$auth->hasIdentity() && $e->getRouteMatch()->getMatchedRouteName() !== 'login/process') {
$application = $e->getTarget();
$e->stopPropagation();
$response = $e->getResponse();
$response->setStatusCode(302);
$response->getHeaders()->addHeaderLine('Location', $e->getRouter()->assemble(array(), array('name' => 'login/process')));
//returning response will cause zf2 to stop further dispatch loop
return $response;
}
}, 100);
}
This is not something that you wanna be doing inside your layout.phtml. Typically you want to hook in to an event that happens before the rendering. In ZF2, the earliest event to hook into that kind of stuff, where it makes sense to hook into, would be the route event. A good diagram of the process that's used in the Authorization-Module BjyAuthorize explains it quite well:
If you don't want to use the Module, you can minify what's happening there, too, like this:
//class Module
public function onBootstrap(MvcEvent $mvcEvent)
{
$eventManager = $mvcEvent->getApplication()->getEventManager();
$eventManager->attach(MvcEvent::EVENT_ROUTE, array($this, 'onRoute'), -1000);
}
public function onRoute(MvcEvent $event)
{
$serviceLocator = $mvcEvent->getApplication()->getServiceLocator();
// From this point onwards you have access to the ServiceLocator and can check
// for an authenticated user and if the user is not logged in, you return a
// Response object with the appropriate ResponseCode redirected and that's it :)
}
I am currently building an Twitter client application for campus project using Codeigniter and Elliot Haughin Twitter library. It's just a standard application like tweetdeck. After login, user will be directed to the profile page containing timline. I am using Jquery to refresh the timeline every 20 second. At the beginning, everything run smoothly until i found the following error at the random time :
![the error][1]
A PHP Error was encountered
Severity: Notice
Message: Undefined property: stdClass::$request
Filename: libraries/tweet.php
Line Number: 205
I already search the web about this error but can't find satisfied explanation. So I tried to find it myself and found that the error comes out because credentials validation error. I tried to var_dump the line $user = $this->tweet->call('get', 'account/verify_credentials'); and resulting an empty array. My question is how come this error showed up when user already login and even after updated some tweets? is there any logical error in my script or is it something wrong with the library? Could anyone explain whats happening to me? please help me...
Here's my codes:
The Constructor Login.php
<?php
class Login extends CI_Controller
{
function __construct()
{
parent::__construct();
$this->load->library('tweet');
$this->load->model('login_model');
}
function index()
{
$this->tweet->enable_debug(TRUE); //activate debug
if(! $this->tweet->logged_in())
{
$this->tweet->set_callback(site_url('login/auth'));
$this->tweet->login();
}
else
{
redirect('profile');
}
}
//authentication function
function auth()
{
$tokens = $this->tweet->get_tokens();
$user = $this->tweet->call('get', 'account/verify_credentials');
$data = array(
'user_id' => $user->id_str,
'username' => $user->screen_name,
'oauth_token' => $tokens['oauth_token'],
'oauth_token_secret' => $tokens['oauth_token_secret'],
'level' => 2,
'join_date' => date("Y-m-d H:i:s")
);
//jika user sudah autentikasi, bikinkan session
if($this->login_model->auth($data) == TRUE)
{
$session_data = array(
'user_id' => $data['user_id'],
'username' => $data['username'],
'is_logged_in' => TRUE
);
$this->session->set_userdata($session_data);
redirect('profile');
}
}
}
profile.php (Constructor)
<?php
class Profile extends CI_Controller
{
function __construct()
{
parent::__construct();
$this->load->library('tweet');
$this->load->model('user_model');
}
function index()
{
if($this->session->userdata('is_logged_in') == TRUE)
{
//jika user telah login tampilkan halaman profile
//load data dari table user
$data['biography'] = $this->user_model->get_user_by_id($this->session->userdata('user_id'));
//load data user dari twitter
$data['user'] = $this->tweet->call('get', 'users/show', array('id' => $this->session->userdata('user_id')));
$data['main_content'] = 'private_profile_view';
$this->load->view('includes/template', $data);
}
else
{
//jika belum redirect ke halaman welcome
redirect('welcome');
}
}
function get_home_timeline()
{
$timeline = $this->tweet->call('get', 'statuses/home_timeline');
echo json_encode($timeline);
}
function get_user_timeline()
{
$timeline = $this->tweet->call('get', 'statuses/user_timeline', array('screen_name' => $this->session->userdata('username')));
echo json_encode($timeline);
}
function get_mentions_timeline()
{
$timeline = $this->tweet->call('get', 'statuses/mentions');
echo json_encode($timeline);
}
function logout()
{
$this->session->sess_destroy();
redirect('welcome');
}
}
/** end of profile **/
Default.js (The javascript for updating timeline)
$(document).ready(function(){
//bikin tampilan timeline jadi tab
$(function() {
$( "#timeline" ).tabs();
});
//home diupdate setiap 20 detik
update_timeline('profile/get_home_timeline', '#home_timeline ul');
var updateInterval = setInterval(function() {
update_timeline('profile/get_home_timeline', '#home_timeline ul');
},20*1000);
//user timeline diupdate pada saat new status di submit
update_timeline('profile/get_user_timeline', '#user_timeline ul');
//mention diupdate setiap 1 menit
update_timeline('profile/get_mentions_timeline', '#mentions_timeline ul');
var updateInterval = setInterval(function() {
update_timeline('profile/get_mentions_timeline', '#mentions_timeline ul');
},60*1000);
});
function update_timeline(method_url, target)
{
//get home timeline
$.ajax({
type: 'GET',
url: method_url,
dataType: 'json',
cache: false,
success: function(result) {
$(target).empty();
for(i=0;i<10;i++){
$(target).append('<li><article><img src="'+ result[i]['user']['profile_image_url'] +'">'+ result[i]['user']['screen_name'] + ''+ linkify(result[i]['text']) +'</li></article>');
}
}
});
}
function linkify(data)
{
var param = data.replace(/(^|\s)#(\w+)/g, '$1#$2');
var param2 = param.replace(/(^|\s)#(\w+)/g, '$1#$2');
return param2;
}
That's the codes. Please help me. After all, I really appreciate all comments and explanation from you guys. Thanks
NB: sorry if i had bad English grammar :-)
You are making a call to statuses/home_timeline which is an unauthenticated call. The rate limit for unauthenticated calls is 150 requests per hour.
Unauthenticated calls are permitted 150 requests per hour.
Unauthenticated calls are measured against the public facing IP of the
server or device making the request.
This would explain why you see the problem at the peak of your testing.
With the way you have it setup you would expire your rate limit after 50 minutes or less.
I suggest changing the interval to a higher number, 30 seconds would do. That way you'll be making 120 requests per hour and under the rate limit.