Flash Message in YII Framework - yii

After I send the request, I will announce the result to the user via SET FLASH. What is the way to show a message when the user sends a request?
For example when sending a message form : Display -> form is being send and then a flash message is displayed

Check the wiki on the Yii framework website:
http://www.yiiframework.com/wiki/21/how-to-work-with-flash-messages/
In your controller you can put:
Yii::app()->user->setFlash('success', "Form posted!");
In your view you can echo the flash message by:
<?php echo Yii::app()->user->getFlash('success'); ?>
Optionally you can check if a flash message exists by using the hasFlash method, so the code in your view would look like this:
<?php if(Yii::app()->user->hasFlash('success')):?>
<?php echo Yii::app()->user->getFlash('success'); ?>
<?php endif; ?>

Add setFlash in your controller. Something like this:
if($comment->save())
{
Yii::app()->user->setFlash('commentSubmitted','Thank you for your comment.');
$this->refresh();
}
And in your views, display flash message something like this:
<?php if(Yii::app()->user->hasFlash('commentSubmitted')): ?>
<div class="flash-success">
<?php echo Yii::app()->user->getFlash('commentSubmitted'); ?>
</div>
<?php endif; ?>

In your controller you can put:
if(conditions)
Yii::app()->user->setFlash('success', "Success text");
else
Yii::app()->user->setFlash('error', "Error text");
In your view you can echo the flash message by:
<?php
if(Yii::app()->user->hasFlash('success'))
Yii::app()->user->setFlash('success', '<strong>Well done!</strong> '.Yii::app()->user->getFlash('success').'.');
else
Yii::app()->user->setFlash('error', '<strong>Error!</strong> '.Yii::app()->user->getFlash('error').'.');
$this->widget('bootstrap.widgets.TbAlert', array(
'block'=>true, // display a larger alert block?
'fade'=>true, // use transitions?
'closeText'=>'×', // close link text - if set to false, no close link is displayed
'alerts'=>array( // configurations per alert type
'success'=>array('block'=>true, 'fade'=>true, 'closeText'=>'×'), // success, info, warning, error or danger
),
)); ?>

Related

how to post login array error within the originating page

Hi how do you post the login error message within the originating page where the user was attempting to login ?
Below I was able to stay on the current page if user login successfully but for login error it will obviously just go to the logonprocess page and display the error message.
Sorry that I remove a lot of validation below as the codes can really be very long.
Index.php
<?php
//set the session cookie parameter
ini_set("session.save_path", "sessionData");
session_start();
?>
<?php
if (!isset($_SESSION['uName'])) { ?>
<form method="post" action="logonProcess.php">
<div>Username <input type="text" name="userName" placeholder="Username"></div>
<div>Password <input type="password" name="pwd" placeholder="Password"></div>
<div><input type="submit" value="Logon"></div>
</form>
<?php } else { }?>
<?php
if (isset($_SESSION['uName'])) {
$username = $_SESSION['uName'];
echo "<p>Welcome $username</p>\n";
?>
Logout</br></br>
LogonProcess.php
$loginerror = array();
if (empty($username)) {
$loginerror[] = "You have not entered all of the required fields";
}
elseif (strlen($passWD) < 8) {
$loginerror[] = "You have not entered all of the required fields";
}
if (!empty($loginerror))
for ($a=0;$a<count($loginerror);$a++)
{
echo "$loginerror[$a] <br />\n";
}
else
if (mysqli_stmt_fetch($stmt))
{
if (password_verify($passWD, $passWDHash))
{
$_SESSION['uName'] = $username;
echo "<p>Login successful</p>";
header('Location: ' . $_SERVER['HTTP_REFERER']);
}
else
{
echo "<p>Please try to login again</p>";
}
why dont you put ur login error in $_SESSION["login_error"] and check in ur origin page if the session exits show the error then destroy the session after it.

Invalid Request YII when delete model via POST

I want delete my model via post , but I always get Invalid Request
this is my view
<?php
echo CHtml::link(CHtml::encode('Delete image'), array('gambar/delete', 'id' => $data->id), array(
'submit' => array('data/delete', 'id' => $data->id),
'class' => 'delete', 'confirm' => 'This will remove the image. Are you sure?'
)
);
?>
and this is my action in GambarController
public function actionDelete() {
if (Yii::app()->request->isPostRequest) {
// we only allow deletion via POST request
$this->loadModel()->delete();
if (!isset($_GET['ajax']))
$this->redirect(array('index'));
}
else
throw new CHttpException(400, 'Invalid request. Please do not repeat this request again.');
}
But I always get Invalid Request, I have read some forums, but I cannot get it. Anyone can help me ?
In most cases you can not use link (<a>) to POST. Instead, use the <form> like this
<form action="<?php echo $this->createUrl('/gambar/delete/'.$model->id);?>" method="post">
<button
type="submit"
name="id"
value="<?php echo $model->id?>"
onclick="if (!confirm('Are you sure to delete this image?')) return false;">
<i class="icon-white icon-trash"></i> Delete
</button>
</form>
You are using CHtml::link, this will generate an html <a> tag. When you click on a <a>, your browser send HTTP GET request(not POST request) to the server. So if(Yii::app()->request->isPostRequest) is always false and therefore you see Invalid request error. You should remove this condition from the action. Also, $this->loadModel()->delete() is invalid, because loadModel get an id as parameter. So $this->loadModel($_GET['id'])->delete() is correct.
Use the below code
$this->loadModel(primarykey, 'TableName')->delete();
Should work!

Getting posts from google plus page

I would like to get content (posts) from a google+ page and post it to my website, as a feed. Is there any info how?
I read that current API does not allow that, but those topics were from the last year.
Thanks.
You can perform activities.list, without having to authenticate, by passing your "simple" key from the API console for a project created that has the Google+ service turned on. Access to the API calls is restricted to the authorized origins you set up in your project.
After you create the project, in the section "Simple API Access" there is an API key. Build your client with this key, your client id, and client secret:
<?
$client = new Google_Client();
$client->setDeveloperKey("YOUR_API_KEY");
$plus = new Google_PlusService($client);
$activities = $plus->activities->listActivities("+GooglePlusDevelopers", "public");
?>
<html><body><pre><? echo print_r($activities);?></pre></body></html>
A final note, make sure you use the latest Google+ PHP client.
After some time I found it.
http://code.google.com/p/google-plus-php-starter/
and this
https://developers.google.com/+/api/latest/activities/list
The only problem is that you need to log into your google app to do this. Any sugggestions would be apprecited.
Updating the correct answer, the class name has changed to Google_Service_Plus
<?php
set_include_path(get_include_path() . PATH_SEPARATOR . __DIR__ .'/vendor/google/apiclient/src');
require_once __DIR__.'/vendor/autoload.php';
$client = new Google_Client();
$client->setDeveloperKey("YOUR_API_KEY");
$plus = new Google_Service_Plus($client);
$activities = $plus->activities->listActivities("+GooglePlusDevelopers", "public");
?>
$items = $activities->getItems();
foreach($items as $item) {
$object = $item->getObject();
?>
<div class="gpost">
<p><?php echo $object->getContent(); ?></p>
Read more
</div>
<?php } ?>

How do correctly authorise a Facebook App

I am creating a basic Facebook app, and when a user without permission visits the app, they are redirected to the authorisation page. However, the page doesn't display, and I see the following error.
This content cannot be displayed in a frame
Opening it in a new window then shows the authorisation page for my app. Clicking 'Go to App' then takes me to the App, but in it's own window, away from Facebook. Going back to FB and reloding the App page now works.
Stranger yet, when I am logged out and go to my app page, I get a Facebook 404 page (4oh4.php).
I'm guessing that I am doing this wrong somehow, so can anyone see anything obvious wrong with my script? Thanks.
To see what is happening - http://apps.facebook.com/dyne_drewett_news/
<?php
require 'fb/facebook.php';
$fbconfig['appUrl'] = 'my-app-url'; // Create An instance of our Facebook Application.
$facebook = new Facebook(array(
'appId' => 'my-app-ID', // Entered correctly in actual script
'secret' => 'me-app-secret', // Entered correctly in actual script
'cookies' => 'true',
));
// Get the app User ID
$user = $facebook->getUser();
if($user) :
try{ // If the user has been authenticated then proceed
$user_profile = $facebook->api('/me');
} catch (FacebookApiException $e){
error_log($e);
$user = null;
}
endif;
// If the user is authenticated then generate the variable for the logout URL
if($user) :
$logoutUrl = $facebook->getLogoutUrl();
?>
<!-- My HTML goes here -->
<?php
else :
$loginUrl = $facebook->getLoginUrl();
header('Location: '.$loginUrl);
endif;
?>
Because you are working in an iframe, you'll have to execute JavaScript redirects. Only that way will you be able to redirect the top most frame -
echo "<script language=javascript>";
echo "top.location.href ='".$url."';";
echo "</script>";
exit();
This is the only way to do complete redirects within a Facebook application. Any other redirect (with PHP for example) will only redirect the user within the iframe...

sfFacebookConnectPlugin: Authentication problem

I try to get the sfFacebookConnectPlugin to run by following the tutorial on the symfony homepage.
Everything seems well configured. But when I try to login with sfFacebookConnectAuth/signin.
I get the form error "The username and/or password is invalid.".
I even don't know where to start with the debugging.
First Step could be to find out the right Application-Settings on the Facebook-Side (e.g. Post-Authorize Callback URL, Connect-URL or Canvas Callback URL)
I use symfony 1.4.5 doctrine with sfGuardDoctrinePlugin (on a live host with subdomain.)
Thx for your help.
I found that page: http://burgiblog.com/2009/09/18/developing-facebook-applications-with-symfony/ now it works, I changed three things after reading the tutorial:
modules/sfFacebookConnectAuth/config/security.yml: Use "false" instead of "off"
I added "callback_url" in apps/frontend/config/app.yml
And I used the facebook action in the tutorial
I need to find out, what the problem exactly was. And I need to enhance some things to the plugin. E.g. saving the user data to my profile class etc. (Now I saves a cryptic username instead of the right FB username.)
It says on the plugin page that this plugin is only supported/stable up to Symfony 1.2. Might make sense to email the plugin author directly regarding 1.4 compatibility.
I'm having some problems with sfFacebookConnectPlugin. I tried replicating the simple example from http://burgiblog.com/2009/09/18/developing-facebook-applications-with-symfony/ . And calling the index page, I get redirected to the facebook authentication page but after logging in, I do not get redirected back. I stay logged into facebook only. What am I doing wrong?
Thanks.
This is my code:
[/frontend/config/app.yml]
# default values
all:
facebook:
api_key: xxx
api_secret: xxx
api_id: xxx
callback_url: 'http://localhost'
redirect_after_connect: false
redirect_after_connect_url: ''
connect_signin_url: 'sfFacebookConnectAuth/signin'
app_url: '/my-app'
guard_adapter: ~
js_framework: none # none, jQuery or prototype.
# It is highly recommended to use a js framework if you want a correct experience in IE
sf_guard_plugin:
profile_class: sfGuardUserProfile
profile_field_name: user_id
profile_facebook_uid_name: facebook_uid # WARNING this column must be of type bigint ! 100000398093902 is a valid uid for example !
profile_email_name: email
profile_email_hash_name: email_hash
facebook_connect:
load_routing: true
user_permissions: []
[layout.php]
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en" xmlns:fb="http://www.facebook.com/2008/fbml">
<head>
<?php use_helper('sfFacebookConnect') ?>
<?php include_http_metas() ?>
<?php include_metas() ?>
<?php include_title() ?>
<link rel="shortcut icon" href="/favicon.ico" />
</head>
<body>
<?php echo $sf_content ?>
<?php include_bottom_facebook_connect_script(); ?>
</body>
</html>
[actions.class.php]
<?php
/**
* facebook actions.
*
* #package
* #subpackage facebook
* #author Your name here
* #version SVN: $Id: actions.class.php 12479 2008-10-31 10:54:40Z fabien $
*/
class homeActions extends sfActions
{
/**
* Executes index action
*
* #param sfRequest $request A request object
*/
public function executeIndex(sfWebRequest $request)
{
sfFacebook::requireLogin();
//get the user object
$user = $this->getUser();
// facebook user id
$this->fb_uid = $user->getCurrentFacebookUid();
// get or create user based on fb_uid
$fb_user = sfFacebook::getOrCreateUserByFacebookUid($this->fb_uid);
}
}
[indexSuccess.php]
<?php if ($sf_user->isFacebookConnected()): ?>
<fb:serverfbml style="width: 740px;">
<script type="text/fbml">
<fb:fbml>
<fb:request-form target="_top" action="[where to redirect after invite]" method="post" type="[name of your app]" content="[text the user will receive]<fb:req-choice url="http://apps.facebook.com/[your app]/" label="Accept!" " image="" invite="true">
<fb:multi-friend-selector cols="4" actiontext="[some text above the invite form]" />
</fb:request-form>
</fb:fbml>
</script>
</fb:serverfbml>
<?php else: ?>
<p>Ooops?</p>
<br />
<?php endif; ?>