I have a small gallery, it has two types of pictures, one is a preview, the other is a regular one, it opens when you click on the preview.
Here is this code, which is on line 173 of the controller:
$model = Gallery::getActive()->where(['code' => $code])->with(
[
'itemsPhoto' => static function (ActiveQuery $query) {
$query->with(['photo', 'preview']);
}
]
)->one();
So, I opened DB debug to look at the requests for this gallery, and I got this:
I have two pictures in my gallery right now. That is, for each picture there is a separate request (preview and regular).
How can I make requests for all pictures in the gallery not come separately, but all together, in one request, should this be done in the controller in this line or in another place?
Related
I have a slider in the index page, which has 3 pictures and this pictures has links. What is the best way to change pictures and links: make db table sliders:
id
pic
link
and work with it, or make in config->settings.php something like this:
<?php
return [
'new_products_count' => 6,
'popular_products_count' => 6,
'paginate' => 20,
'admin_paginate' => 10,
'slider'=>[
1=>['img'=>'1.jpg','link'=>'www1'],
2=>['img'=>'2.jpg','link'=>'www2'],
3=>['img'=>'3.jpg','link'=>'www3']
]
];
and work with it like this:
Config::set('settings.slider[1]['img']=>'newimg.jpg')
Config::set('settings.slider[1]['link']=>'newWWW')
?
Would be safer to keep in the database for a couple of reasons.
1- If you cache your configuration, it may sometimes behave like a buggy application. I mean after changing an image and coming back, you may see the previous image displaying again. Because what you change at runtime is not persisted. Try to update a config option, e.g:
config(['database.connections.sqlite.driver' => 'fake']);
Then go check the file. tadaaa... the file didn't change.
2- You database is unlimited. YOu can add an infinite number of images (links) with much more options. Of course, you can also pass options to config() but using Eloquent or Query builder is more flexible.
I'm building a feature into a Laravel 5 app that will allow you to set the content of a status banner that will display across the top of the page. We will be using this banner both to display page-specific things (status messages, etc) and site-wide announcements (every user sees the same thing, banner stays the same for awhile).
Right now, I've implemented this by using Laravel sessions to allow banners to be added by calling a helper method from any controller or middleware:
// Call set_banner from in a controller or middleware (for persistent banners)
function set_banner($banner_text, $banner_class, $banner_persistant=false, $replace=false)
{
$banners = session()->get('banners', []);
// Create new banner
$banner = [
'text' => $banner_text,
'type' => $banner_class,
'persistent' => $banner_persistant
];
// Only put banner in array if it's not already there
if( !in_array($banner, $banners) ) {
// Either override existing banners, or add to queue
if( !$replace ) session()->push('banners', $banner);
else session()->put('banners', [$banner]);
}
}
// Called by default in the master.blade.php template
function get_banners()
{
$banners = session()->pull('banners', Array());
foreach( $banners as $banner ) {
// Print out each banner
print '<div class="col-md-12"><div class="text-center alert alert-block alert-'.$banner['type'].'">';
print $banner['text'];
print '</div></div>';
// Push back into the session if banner is marked as persistent
if ( $banner['persistent'] ) session()->push( 'banners', $banner );
}
}
Banners are created in controllers or middleware like this:
set_banner("<b>Note:</b> This is a sample persistant-scope banner set in a controller", "success", true);
Is there a better way to accomplish storing both page-level and site-wide banners? My concerns is that hitting the session on every pageload may be inefficient, especially for banners that won't be changing for long periods of time. Will this approach mess with Laravel's cache, etc?
As you said the banners do not change that often. Hence for me i would implement it using Cache. This improves performance since we need only one use to have the banners cached. And for the rest its retrieved faster from the Cache rather Session.
Do you want to have to change code to change the banner of a given page?
I would suggest instead creating a "pages" package, where each page route name is entered into a database.
From there, from your page service provider you get Page::getModel()->banner_text or something similar.
The method would look for a db result matching the current route name with a result within db.
when a controller method is triggered you simply call
Page::getBannerText()
That method will pull the current route name, pull the page result related to that page if it exists or create it if it does not exist (easy way to get everything). You cache the db query result for X hours, days or whatever so whenever someone else makes a call, you don't even need to deal with any storage on client side.
This allows you to modify the value from a db fascet. Its the more "proper" way to do it.
I'm confident about posting multiple photos to a fan page album through a common batch request with PHP, and I also know how to use che "no_story" command to hide the wall posts showing each image just uploaded. What I need to know is if it's possible to show an unique wall post on the fan page showing the whole upload, like the standard Facebook behavior when you upload more pictures using the web interface, and not one post for each photos.
This is the closest I have got:
$attachment = array
(
'access_token'=>$fanPageAccessToken,
'object_id' => $AlbumId,
'message' => $AlbumDesc,
'link' =>$AlbumLink
);
$result = $facebook->api($fanPageId.'/links/','post',$attachment);
}
I get the variables by querying the albums associated with the fanpage:
$fanPageAlbums = $facebook->api($fanPageId . '/albums/');
foreach ($this->fanPageAlbums['data'] as $fanPageAlbum) {
if ($albumId == $fanPageAlbum['id']) {
$albumLink = $fanPageAlbum['link'];
$albumDesc = $fanPageAlbum['description'];
break;
}
}
The key thing is your are posting to the links part of the graph, not the feed.
This works in that it will produce one big picture and three thumbs below it, as you would expect. However, it doesn't appear on the feeds of friends properly.
I've been struggling with this for ages, and the above is the closest I have got to mimicing exactly the facebook behavior. If you get any further please let me know!
I would like to create a button that can be used to populate a table in my db with a single click.
I am just not sure what I need to do here to make this happen. Can I assign a method to be executed by a button? Or just have values picked up in my controller? Below is something like what I want to execute but through a button.
public function addInterest($interest)
{
$interest->UserId=Yii::app()->user->id;
$interest->ItemId=$this->ItemId;
return $interest->save();
}
**Additional details in response to Jaison Justus
With this implementation I am using controller and view from Model A (ItemId) where the button is to be displayed. Then there is Model B (UserId). Taking the info from Model A (ItemId) and Model B (UserId) I want to populate Model C ($interest) with that ItemId and UserId upon clicking a button. Looks like CJuiButton might provide a means to build it from being as then I can disable/hide the button after selected once. I am just not familiar with using buttons other than on a form where user input in collected, as links, or to provide pop up messages.
The code above currently sits in Model A model. With the code below in Model A controller everything works to populate Model C if I use a form and collect input. Since I do not require any input other then selecting the button from the user the form has nothing to put into it and therefore I know I can not use if(isset($_POST['Interest'])) as I have below.
public function actionView($id) {
$items=$this->loadModel($id);
$interest=$this->newInterest($items);
$this->render('view', array(
'model' => $items,
'interest' => $interest,
));
}
protected function newInterest($items)
{
$interest=new Interest;
if(isset($_POST['Interest']))
{
$interest->attributes=$_POST['interest'];
if($items->addInterest($interest))
$this->refresh();
}
return $interest;
}
In response to VarioN
Here is an attempt at using ajax. However this does not work and gives an Error 500 when ran. Is my controller action appropriate for what I am trying to do here?
Controller
public function actionAddInterest() {
$connection = yii::app()->db;
$sql1 = "INSERT INTO interest (UserId, ItemId)
VALUES(".Yii::app()->user->id.",".$this->ItemId.")";
$connection->createCommand($sql1)->execute();
}
View
<?php
echo CHtml::ajaxLink(
'Add Interest',
array('/item/addInterest'),
array('update'=>'#req_res')
);
?>
Looking at your question I see that you don't understand how MVC in Yii works.
Look at this 15 minutes screencast (Yii Tour - 3rd Stop - CRUD County) and after you will be able to create such button in any way you need (try use Gii and than customize it in your way - it's the easiest way).
Updated:
Seems that you need AJAX request. You can add CHtml::ajaxButton() in your view.
It will work this way:
User push the button, button do request (with JavaScript) to your
site without reloading the page and invisible for user.
Your controller action will serve this request: it can make some things (for ex., save data to db) and output data that your JavaScript possibly will display to user.
Than your JavaScript get answer and can make some changes on the page
(for example, hide button or show text got from request).
You can look at simple example with ajax here
If you needn't to submit form info with your button you can user ajaxLink. Example for it is here
There are a lot of examples with ajax and yii in the internet and at yii forum. Try to find them it may be very helpful.
Ask questions if you would have any.
Second update:
First, try to do your sql query simplier:
"INSERT INTO interest (UserId, ItemId) VALUES (1, 2)"
Than enable logging of mysql queries to log: at config/main.php add "trace" to "levels"
'components'=>array(
'log'=>array(
'class'=>'CLogRouter',
'routes'=>array(
array(
'class'=>'CFileLogRoute',
'levels'=>'error, warning, trace',
),
Now you can try to press an AJAX link and look at the protected/runtime/log.txt and determine the problem.
Additional info to AJAX requests
All that outputs your ajax scripts can be viewed by browser's features:
At Chrome: press F12, go to Network, press an ajax-link and look at request response.
At Firefox with addon "Firebug".
With this you can determine whether a request is done or not.
The question is pretty much in the title, but to be more specific, I'm working on a facebook contest for a client in which people have to upload photos to take part in it after accepting rules and subscribing, etc.
After going down a long road full of deceptions
(here's what I tried that didn't work in the end:
uploading to the user's album then tagging the page: nope, can't tag a page
uploading to a public album in the page, like "fan photos", or wall photos? can't find anything AT ALL about a way to do this, though it would've been my preferred way.)
So, I ended up having an idea: I would do this in two steps. First, the user subsribes and uploads a photo to my PHP server. Then, another, different application with permissions on the account that has the page, would take control of it, upload all the photos at 5 minutes intervals (meaning, you subsribe, 5 minutes later, your photo's uploaded.)
So far, so good; I don't like the logic behind this, but it's the only way I found! So, I did the base, I'm able to post a photo with a caption as the page in a dedicated app album.
BUT! I can't tag anyone in those photos. Maybe you can't tag as a page, maybe you can't tag in page albums, maybe I don't have the permissions required (I have stream_publish, user_photos, friends_photos, offline_access, and I could add anything if I need to since it's a private-use app anyway). Oh and, the user I'm trying to tag is the admin for both the app and the page (and he likes the page). I don't know, but it's driving me crazy. I hate the official documentation, there's no example code, you have to figure out most of the things, go through trial and error or search on the web for people who did so and shared how to do things. Not nice when you have little time to complete a project for a client without busting the budget.
Anyway, here's my error I keep getting whenever I try to tag someone to a photo from any album:
OAuthException: (#322) Invalid photo tag subject
And here's the code I'm using to upload a photo from the server to facebook.
if ($user) {
try {
$page_info = $facebook->api("/$page_id?fields=access_token");
if( !empty($page_info['access_token']) ) {
// First method, at the same time as upload. Upload works but no tags
$args = array(
'access_token' => $page_info['access_token'],
'source' => '#' . realpath($FILE_PATH),
'message' => "test"
'tags' => array(
array(
'tag_uid'=> "MY_USER_ID",
'x' => 0,
'y' => 0
))
);
$post = $facebook->api("/$page_id/photos","post",$args);
$postID = $post['id'];
// Second method I'm trying. No tags.
$tag = $facebook->api("/$postID/tags/MY_USER_ID","post");
print_r($tag);
}
} catch (FacebookApiException $e) {
error_log($e);
$user = null;
}
}
Any help would be appreciated. Thanks in advance!
EDIT :: Now I got it partly working using the second part in the code, but only if I remove the "access_token" parameter from the photo posting first. Basically, it only works if I upload it to a personal album. But that's as far as it gets from what I want. When I upload it to the album from the page, it says I asked for tag requests, but on my personal account which I tagged, I don't receive anything. Baaaah.
RE-EDIT :: After much tries, it seems I can't tag someone as a page or in a page album. I'll try to find an alternative, I guess.