Cake PHP drop down list - list

I would like to know how to add a drop down list for "access control" with value "staff" and "Admin".
This is my add function in employee controller
public function add() {
if ($this->request->is('post')) {
$this->Employee->create();
if ($this->Employee->save($this->request->data)) {
$this->Session->setFlash(__('The employee has been saved.'));
return $this->redirect(array('action' => 'index'));
} else {
$this->Session->setFlash(__('The employee could not be saved. Please, try again.'));
}
}
}
This is the add view code:
<div class="employees form">
<?php echo $this->Form->create('Employee'); ?>
<fieldset>
<legend><?php echo __('Add Employee Details'); ?></legend>
<?php
echo $this->Form->input('employee_name');
echo $this->Form->input('date_hired', array('dateFormat' => 'DMY','minYear'=>date('Y')-100, 'maxYear'=>date('Y')+100));
echo $this->Form->input('employee_phone_number');
echo $this->Form->input('employee_email');
echo $this->Form->input('employee_address');
echo $this->Form->input('employee_dob', array('dateFormat' => 'DMY','minYear'=>date('Y')-100, 'maxYear'=>date('Y')+100));
echo $this->Form->input('access_level');
echo $this->Form->input('employee_username');
echo $this->Form->input('employee_pw');
?>
</fieldset>
<?php echo $this->Form->end(__('Submit')); ?>
</div>

To add a drop down list for access control with value staff and Admin.
add this in your employee controller
$customers = $this->Employee->modelname->find('list');
$this->set(compact('customers'));
and in view.ctp
echo $this->Form->input('access_level');

If you are getting access_level data from database then-
echo $this->Form->input('access_level', array('options' => array('admin' => 'Admin', 'staff' => 'Ataff')));

Related

"The domain of this URL isn't included in the app's domains" when it is

I'm trying to post to a Facebook wall from a PHP script. I've created a FB app, installed the Graph PHP API, and implemented some test scripts as follows:
fbinit.php:
<?php
session_start();
require_once('src/Facebook/autoload.php');
$fb = new Facebook\Facebook([
'app_id' => 'REDACTED',
'app_secret' => 'REDACTED',
'default_graph_version' => 'v2.9',
]);
?>
fbpost.php:
<?php
include('fbinit.php');
$helper = $fb->getRedirectLoginHelper();
$permissions = ['manage_pages','publish_pages']; //'publish_actions'
$loginUrl = $helper->getLoginUrl('https://www.REDACTED.net/fb-callback.php', $permissions);
echo 'Log in with Facebook!';
?>
fb-callback.php:
<?php
include('fbinit.php');
$helper = $fb->getRedirectLoginHelper();
$_SESSION['FBRLH_state']=$_GET['state'];
try {
$accessToken = $helper->getAccessToken();
} catch(Facebook\Exceptions\FacebookResponseException $e) {
echo 'Graph returned an error: ' . $e->getMessage();
exit;
} catch(Facebook\Exceptions\FacebookSDKException $e) {
echo 'Facebook SDK returned an error: ' . $e->getMessage();
exit;
}
if (! isset($accessToken)) {
echo 'No OAuth data could be obtained from the signed request. User has not authorized your app yet.';
exit;
}
try {
$response = $fb->get('me/accounts', $accessToken->getValue());
$response = $response->getDecodedBody();
} catch(Facebook\Exceptions\FacebookResponseException $e) {
echo 'Graph returned an error: ' . $e->getMessage();
exit;
} catch(Facebook\Exceptions\FacebookSDKException $e) {
echo 'Facebook SDK returned an error: ' . $e->getMessage();
exit;
}
echo "<pre>";
print_r($response);
echo "</pre>";
?>
The first time I opened fbpost.php, I was asked to log in to Facebook as expected, and it asked for permission to post on my behalf on the page, which is fine. But then I am redirected to the call back page and presented with the following error:
Graph returned an error: Can't load URL: The domain of this URL isn't included in the app's domains. To be able to load this URL, add all domains and sub-domains of your app to the App Domains field in your app settings.
I have added every combination of the app URL's and callback URL's I can think of, but nothing works. See below for screenshots of the app settings. The App ID and secret are definitely correct.
The value of the redirect_uri parameter needs to be the exact same in your login dialog call, and the subsequent API call that tries to exchange the code for a token.
When you have generation of the login URL and handling of the response spread over different scripts (i.e., called via different URLs), that can easily lead to problems like this. The SDK tries to figure out the value based on the current script URL, if left to its own devices.
In such a case, explicitly specify the callback URL in your getAccessToken method call as well.

Error while posting on Facebook using Facebook Graph v5 sdk

I'm using Facebook Graph v5 sdk for login and posting on wall but gets some errors. I've successful login and gets users details like age, birthday etc. successfully but while on posting on facebook using this code
$fb->post('/me/feed', $attachment, $accessToken);
gets some permissions errors as below.
Error:
Fatal error: Uncaught Facebook\Exceptions\FacebookAuthorizationException: (#200) Requires either publish_actions permission, or manage_pages and publish_pages as an admin with sufficient administrative permission
index.php
<?php
require_once "config.php";
$redirectURL = "http://localhost/fbLogin/fb-callback.php";
$permissions = ['email, user_birthday,user_posts,manage_pages,publish_pages'];
$loginURL = $helper->getLoginUrl($redirectURL, $permissions);
echo $loginURL;
?>
<!DOCTYPE html>
<html>
<head>
<title></title>
</head>
<body>
<button onclick="myFunction()">Click me</button>
<script>
function myFunction() {
window.location = "<?php echo $loginURL; ?>";
}
</script>
</body>
</html>
fb-callback.php
<?php
require_once "config.php";
try {
$accessToken = $helper->getAccessToken();
} catch(\fbLogin\Exceptions\FacebookResponseException $e) {
echo $e->getMessage();
exit();
} catch(\fbLogin\Exceptions\FacebookResponseException $d) {
echo $d->getMessage();
exit();
}
if (!isset($accessToken)) {
if ($helper->getError()) {
header('HTTP/1.0 401 Unauthorized');
echo "Error: " . $helper->getError() . "\n";
echo "Error Code: " . $helper->getErrorCode() . "\n";
echo "Error Reason: " . $helper->getErrorReason() . "\n";
echo "Error Description: " . $helper->getErrorDescription() . "\n";
} else {
header('HTTP/1.0 400 Bad Request');
echo 'Bad request';
}
exit;
}
// Logged in
echo '<h3>Access Token</h3>';
var_dump($accessToken->getValue());
// The OAuth 2.0 client handler helps us manage access tokens
$oAuth2Client = $fb->getOAuth2Client();
// Get the access token metadata from /debug_token
$tokenMetadata = $oAuth2Client->debugToken($accessToken);
echo '<h3>Metadata</h3>';
var_dump($tokenMetadata);
// Validation (these will throw FacebookSDKException's when they fail)
$tokenMetadata->validateAppId('371331840061100'); // Replace {app-id} with your app id
// If you know the user ID this access token belongs to, you can validate it here
//$tokenMetadata->validateUserId('123');
$tokenMetadata->validateExpiration();
if (! $accessToken->isLongLived()) {
// Exchanges a short-lived access token for a long-lived one
try {
$accessToken = $oAuth2Client->getLongLivedAccessToken($accessToken);
} catch (Facebook\Exceptions\FacebookSDKException $e) {
echo "<p>Error getting long-lived access token: " . $e->getMessage() . "</p>\n\n";
exit;
}
echo '<h3>Long-lived</h3>';
var_dump($accessToken->getValue());
}
$_SESSION['fb_access_token'] = (string) $accessToken;
$respose = $fb->get("/me?fields=id,name,email,first_name,last_name,address,hometown,gender,birthday,posts", $accessToken);
// Get the base class GraphNode from the response
$graphNode = $respose->getGraphNode();
// Get the response typed as a GraphUser
$user = $respose->getGraphUser();
echo $user->getName();
echo $user->getEmail();
echo $user->getBirthday()->format('m/d/y');
echo $graphNode->getField('country');
echo $user->getHomeTown();
echo $user->getGender();
echo $_SESSION['fb_access_token'];
header('Location: http://localhost/fblogin/home.php');
?>
config.php
<?php
session_start();
require_once "Facebook/autoload.php";
$fb = new \Facebook\Facebook([
'app_id' => '371331840061100',
'app_secret' =>'fc535825bfe084a63c33a6d36648ddff',
'default_graph_version' => 'v2.10'
]);
$helper = $fb->getRedirectLoginHelper();
?>
home.php
<?php
require_once "config.php";
?>
<!DOCTYPE html>
<html>
<head>
<title></title>
</head>
<body>
<h1>wlecom</h1>
<?php
$message = "test message";
$attachment = array('message' => $message);
try{
$accessToken = $_SESSION['fb_access_token'];
// Post to Facebook
$fb->post('/me/feed', $attachment, $accessToken);
// Display post submission status
echo 'The post was published successfully to the Facebook timeline.';
}catch(FacebookResponseException $e){
echo 'Graph returned an error: ' . $e->getMessage();
exit;
}catch(FacebookSDKException $e){
echo 'Facebook SDK returned an error: ' . $e->getMessage();
exit;
} catch(\fbLogin\Exceptions\FacebookResponseException $e) {
echo $e->getMessage();
exit();
} catch(\fbLogin\Exceptions\FacebookResponseException $d) {
echo $d->getMessage();
exit();
}
?>
</body>
</html>
It seems that you are trying to post on a user wall with a token that does not include the publish_actions permission.
You should read the changelog about publish_actions first though: https://developers.facebook.com/docs/graph-api/changelog/breaking-changes

Opencart 2.3.0.2 Category foreach products as product clone without limit

I am not sure if this is possible but I am trying to show my products twice on the category.tpl, once as standard with the limit and pagination. The other so it just shows every single product in that category that is on special offer no limits or paginations.
I plan to have a tab / accordion style where you can click to see all products (limited to 10 per page with multiple pages) or all products on the one page that are on special offer (no limits).
There are possibly ways of doing this by filter but I would really like to get it to work separately within the category.php (controller). Or better still if I could get it to work together with the current array the products use (not sure if that would be possible to differentiate).
So far I have tried cloning the products data array in the controller to try and make it work on it's own without limit - the closest I can get is where it only shows the products on special offer from the current pagination.
Here is what I've got at the moment (currently php error message: Undefined index: special - from the category.tpl if statement):
Category.php (controller)
$data['specials'] = array();
$filter_specials = array(
'filter_category_id' => $category_id,
'filter_filter' => $filter,
'sort' => $sort,
'start' => ($page - 1) * $limit * 0,
'limit' => 10000
);
$specials = $this->model_catalog_product->getProducts($filter_specials);
foreach ($specials as $result) {
$data['specials'][] = array(
'product_id' => $result['product_id'],
'name' => $result['name'],
'price' => $price,
'special' => $special,
);
}
I have tried to mimic the results as result that the products use in the category.php.
Category.tpl:
<?php foreach ($specials as $product) { ?>
<?php if ($product['special']) { ?>
<?php echo $product['name']; ?></h4>
<?php } ?>
<?php } ?>
Any help would be really appreciated!

adding like comment issue using graph api

i have put last 3 posts in web page , if user loged in he can add comment / like , problem is if user loged in and try add like or comment he is getting an permission error #200 , if i loged in i can add like or comment (application is for me) , am getting the all permission nedded from the user , so how can i give him permission to add like / comment.
CODE :
$facebook = new Facebook(array(
'appId' => '',
'secret' => '',
'cookie' => true,
));
$user = $facebook->getUser();
if ($user) {
if (session_id()) {
} else {
session_start();
}
$access_token = $facebook->getAccessToken();
//check permissions list
$permissions_list = $facebook->api(
'/me/permissions', 'GET', array(
'access_token' => $access_token
)
);
//check if the permissions we need have been allowed by the user
//if not then redirect them again to facebook's permissions page
$permissions_needed = array('publish_stream', 'read_stream', 'manage_pages');
foreach ($permissions_needed as $perm) {
if (!isset($permissions_list['data'][0][$perm]) || $permissions_list['data'][0][$perm] != 1) {
$login_url_params = array(
'scope' => 'publish_stream,read_stream,manage_pages',
'fbconnect' => 1,
'display' => "page",
'redirect_uri' => 'http://localhost/fb/index.php',
);
$login_url = $facebook->getLoginUrl($login_url_params);
header("Location: {$login_url}");
exit();
}
}
}else {
//if not, let's redirect to the ALLOW page so we can get access
//Create a login URL using the Facebook library's getLoginUrl() method
$login_url_params = array(
'scope' => 'publish_stream,read_stream,manage_pages',
'fbconnect' => 1,
'display' => "page",
'redirect_uri'=>'http://localhost/fb/index.php',
);
$login_url = $facebook->getLoginUrl($login_url_params);
//redirect to the login URL on facebook
header("Location: {$login_url}");
exit();
}
$logoutUrl = $facebook->getLogoutUrl();
and if the user click on like button :
jQuery('ul.fb_list a').click(function(){
var comm_id = jQuery(this).attr("class");
jQuery.post('https://graph.facebook.com/'+comm_id+'/likes/',{
access_token : "<?php echo $access_token ?>"
});
});
Double check and make sure your variable comm_id is formated with both the user id of the person who posted the post, and then the id of the post itself, with an underscore in between, like this - USERID_POSTID. This is how facebook gives it you if you call to the graph api
$post_url = "https://graph.facebook.com/" . $user_id . "/posts?access_token=". urlencode($access_token);
Not sure if you're getting comm_id from another source or not. Also noticed in your code
access_token : "<?php echo $access_token ?>"
You forgot a semi-colon after the echo call. Should be this
access_token : "<?php echo $access_token; ?>"
Hope this helps. I see you're using a lot of jquery to do the like functionality. I like to stick w/ server side code for stuff like this, I feel that it's more stable for some reason.
This is how I did it. I have a like button like this -
echo '<div id="like_container-'.$i.'">
<div id="like_count">'.$num_likes.'</div>'
<div class="unliked"></div>
</div>';
and fb_Like() is an ajax call, something like this -
function fb_Like(post_id, token, num_likes, id){
$.ajax({
type: "GET",
url: "likepost.php",
data: 'id='+post_id+'&token='+token+'&likes='+num_likes,
success: function(html)
{
$("#like_container-"+id).empty().html(html);
}
});
}
And the likepost.php page is a script similar to the one on this page
Like a Facebook Post externally using Graph Api - example
This worked really well for me. It also let's me update the number of likes that the post has on the front end right above the like button if a like has been made. Good luck!
UPDATE
If you want to check if the user already likes a post, it's pretty simple w/ the facebook graph api
//Create Post Url
$post_url = "https://graph.facebook.com/" . $Page/User_id . "/posts?access_token=". urlencode($access_token);
//Get Json Contents
$resp = file_get_contents($post_url,0,null,null);
//Store Post Entries as Array
$the_posts = json_decode($resp, true);
foreach ($the_posts['data'] as $postdata) {
foreach ($postdata['likes']['data'] as $like){
if($like['id']==$user){
$liked=1;
}else{continue;}
}
if($liked==1){
//do something
}
}
This assumes that you already have a facebook user id for the logged in user, in this example, stored in the variable $user.

How do I get Permission to post to Facebook Page Wall

After reading the developers.facebook.com for the past few hours I just can't seem to figure out how to get my Facebook Page to allow permission for me to post to its wall from a Django Website?
you must give related permissions to your app(publish_stream,manage pages)
then you can post to page as page
posting to page as page if you have page's access_token can be like this:
include_once ('src/facebook.php');/// include sdk
////// config The sdk
# $facebook = new Facebook(array(
'appId' => 'XXXXXXX',
'secret' => 'XXXXXXXXXXXXXX',
));
try{
$post=$facebook->api('PAGE_ID/feed/','POST',array(
'message' => '$message',
'link'=>'http://apps.facebook.com/xxxxxxx/link.php?link=',
'picture'=> 'XXXXXXXXXX',
'name'=>'XXXXXX',
'description'=>'yes',
'access_token'=>'PAGE ACCESS TOKEN'
));
}
catch(FacebookApiException $e) {
echo $e->getType();
echo '<br />';
echo $e->getMessage();
}
& if you dont have access token (you need above permissions again) i think this can help you
include_once ('src/facebook.php');/// include sdk
////// config The sdk
# $facebook = new Facebook(array(
'appId' => 'XXXXXXX',
'secret' => 'XXXXXXXXXXXXXX',
));
$facebook->destroySession();
try{
$post=$facebook->api('PAGE ID/feed/','POST',array(
'message' => '$message',
'link'=>'http://apps.facebook.com/xxxxxxx/link.php?link=',
'picture'=> 'XXXXXXXXXX',
'name'=>'XXXXXX',
'description'=>'yes',
));
}
catch(FacebookApiException $e) {
echo $e->getType();
echo '<br />';
echo $e->getMessage();
}
to learn how to get page's access_token check this link up:
https://developers.facebook.com/tools/explorer/?method=GET&path=me%2Faccounts