Author Archives: astaz3l

Render block programmatically using Drupal 7

Render block programmatically using Drupal 7 - tutorialHi, folks:)

Render block programmatically - popular topic from google. Today I will tell you a little bit about Drupal Views and how to do that from code. Sometimes we need to render block in our template. For example you created block using Views. You want to place it in the template. In Drupal 7 there are couple of ways to solve this problem. I will show you the 4 methods that will help you render block programmatically. All was checked in Drupal 7.

How to render block programmatically?

Method 1

Let's assume, that you know your view name and block id. If you don't know you can learn how to check that here. In our case view name is sidebar and display id is article_ad. Simplest usage here:

print views_embed_view('sidebar', 'article_ad');

This code will return html markup for our block. Function views_embed_view can take few parameters.

  • name - view name
  • display_id - display id of view we want to render, by default it's 'default'
  • arguments - if you have any parameters you want to pass to block you want to render from code, like contextual filters, you can pass it there via arguments.

Note, that this function does not render block title. If you look to the code of this function you will find out that it's using views_get_view function. It provides more functionality, we will be talking about this approach later (method 4).

Method 2

In second method we will render block programmatically by module_invoke function. Let's look at the example below:

$block = module_invoke('views', 'block_view', 'sidebar-article_ad');
print render($block);

There are 3 parameters, but you can specify more. Just pass more parameters like in previous example to module_invoke function. First two parameters are constant for getting blocks. You have to specify 'views' as a module and 'block_view' as a hook. Next parameter is combination of name and display_id of our block. If you are not sure of the combination, or combination you have provided doesn't work, check it in your database.

In Drupal database there is table called block. In delta column you will find all blocks, that you can use. You can find your block executing query like this

SELECT * FROM block WHERE delta LIKE '%article_ad%'

Find your block in the query results and pass it as 3rd parameter to module_invoke.

Method 3

In 3rd method we will render block programmatically by block_load function. Take a look at example below.

As You can see, there's 'sidebar-article_ad' from previous method. Rest is just copy and paste code.

$block = block_load('views', 'sidebar-article_ad');
print render(_block_get_renderable_array(_block_render_blocks(array($block))));

OK, so here is the method I don't really like. It's hard to pass custom contextual filter value. By default it will take arguments from $_GET. If you know how to do that please write it in comments below:) Any solution will be appreciated:)

So there are two parameters, 'views' and combination of view name and display_id from previous examples.

Method 4

OK, so here is probably most advanced example if you want to render block programmatically. Here you can customize almost every View aspect.

$view = views_get_view('sidebar');
print $view->preview('article_ad');

We are using views_get_view function which returns view object. Take a look at the documentation here:

https://api.drupal.org/api/views/includes!view.inc/class/view/7

You will find there many useful methods, for customization of output, filters and basically everything:P

Getting data from block

OK, now we know how to get html code of your block. But hmmm, what if I need the raw data from my block after passing all contextual filters etc? I don't need html, I will not parse this code via regex or something... I'm not that stupid:P

Not a problem, just use views_get_view_result function. Example usage:

$block_data = views_get_view_result('sidebar', 'article_ad');
print_r($block_data);

It will return you all the data connected with your block. Function takes 2 parameters view name and display_id(block id). After that you can specify additional parameters that will be passed as arguments, like in previous examples.

Drupal 7 Ajax and Views

Drupal Views AjaxHello everybody!

Today I want to share some technique that we are using in our Drupal projects a lot. Sometimes we need button like load more, which will send custom ajax. Default drupal mechanism for ajax is not perfect. What if you will want to modify the result? So I will show you simple example of how to use custom Drupal views ajax. We are using Drupal 7 with Views module.

Using drupal views ajax

Let's look at the snippet below. This basic piece of code will help you with drupal views ajax.

$.ajax({
    url: Drupal.settings.basePath + 'views/ajax',
    type: 'post',
    data: {
        view_name: 'view_name',
        view_display_id: 'view_display_id'
    },
    dataType: 'json',
    success: function (response) {
        if (response[1] !== undefined) {
            var viewHtml = response[1].data;
            //...
            Drupal.attachBehaviors();
        }
    }
});

First of all, it's based on jQuery. If you want to use it in different framework, you can use similar parameters, it should work without any problems:)

OK, so let's analyze this snippet. There are few important lines of code:

url: Drupal.settings.basePath + 'views/ajax',

First is the URL. You can leave it as it is. Drupal.settings.basePath returns base path to your website like http://mywebsite.com/. Than we are using default drupal views ajax mechanism (views/ajax). You can send it as GET or POST request. It is up to you which one you want to use.

data: {
        view_name: 'view_name',
        view_display_id: 'view_display_id'
    },

This is important part. In order to get data from our view, you have to know it's name and display_id. This informations are available in admin panel (look at the screenshot below)

Click Structure -> Views -> {Name of your view} -> Edit

Drupal Views screenshot

 

In our case we will use Question List view. After that pick the page/block you want to get via ajax.

Drupal Views page screenshot

In our case we are using DMP Q&A page. Our machine name of this page is page_4. If it's the only page click on it again and notice the URL change. In our case URL looks like this:

URL for Drupal Views Ajax

 

 

The highlighted parts are the informations we need.

  • questions_list is our view_name
  • page_4 is our view_display_id

This are two most important parameters. You can use more parameters, but it depends on the view and what you want to do with it. For example if you want to load more result you can use per_page parameter and page with stands for numbers of item displayed per page and number of page (first page is 0, second is 1). But remember, if you want to use pagination like that you have to turn it on in view in pager section. If it'll be turned off it won't work. You can use filters values etc. Everything depends on you view configuration.

if (response[1] !== undefined) {
    var viewHtml = response[1].data;
    //...
    Drupal.attachBehaviors();
}

In success function we handle response from server.

First we have to check if there's any result. Drupal will send you response of 2 elements array. Stuff that we need is in [1] element. If there is no [1] element, it means that probably you are passing wrong data. Check it again! In viewHtml we have html data from our view. You can append it, modify it, play as you like.

It's good to use

Drupal.attachBehaviors();

after changing your html code. It will attach certain javascript behaviors  to the new ajaxed content.

Practical example of Drupal Views Ajax

Practical example of drupal ajax views for fetching second page of questions here (using Questions List and DMP Q&A):

$.ajax({
    url: Drupal.settings.basePath + 'views/ajax',
    type: 'post',
    data: {
        view_name: 'questions_list',
        view_display_id: 'page_4',
        per_page: 12,
        page: 1
    },
    dataType: 'json',
    success: function (response) {
        if (response[1] !== undefined) {
            var viewHtml = response[1].data;
            $('#question-container').append(viewHtml);
            Drupal.attachBehaviors();
        }
    }
});

 

Any questions? Or maybe you have better solution?

 

not_authorized Facebook problem

not_authorized status when Facebook Connectnot_authorized problem

Today I have huge problem with facebook connect. I've recieved not_authorized status when I tried to login to my website as facebook user.

But first thing first. I have tried to use FB connect on my websites, and everything works fine for me. Usually I'm using Firefox for daily work. So I've created app on facebook, and leave default settings for it. I've used Facebook SDK for JavaScript. After implementation and first tests It worked fine for me - I could login normally. But today product owner told me that he can't login via Facebook Connect on two different PCs. He used two different accounts, and he couldn't login on any of them...

So OK, we have problem that needs to be solved. He's using chrome on windows and safari on mac for his daily work. I've tested it in on my facebook account on every browser and I could login everywhere. So I tried to use my second facebook account for tests. And actually I have problem with login xD After clicking the Connect button, facebook dialog with authorization closed immediately. What the ...? After checking response from server I found what the problem was: not_authorized status every time. So I was checking multiple things that can be wrong

  • My app wasn't in application center, so I couldn't removed it and try re-auth
  • Our server is running on varnish so maybe there was the problem? But I can login with my second account so it's not that.
  • I cleared all possible caches (drupal cache, browser cache, varnish cache, delete all cookies) - not_authorized
  • I debugged all login code and still nothing. Status was always not_authorized
  • I checked all docs for facebook login searching for ultimate solution and still nothing
  • I asked around about my problem but no one knows the solution...

And FINALLY I've checked the developers.facebook.com for my app. I've noticed that "Sandbox mode" is ON and only administrators, developers and testers has access to my app..... epic fail xD

Solution

After turning sandbox mode off, any facebook user can login via FB connect. not_authorized is gone!

It's now default facebook settings after you create new application (sandbox mode on). So just be sure to turn it off before you go live with your website or add testers to your access list before you launch your product.

 

 

cURL CURLOPT_FOLLOWLOCATION issue with safe_mode/open_basedir

CURLOPT_FOLLOWLOCATION doesn't workToday I've encountered problem with the CURLOPT_FOLLOWLOCATION. I tried to get user profile picture from facebook with cURL. Unfortunately, on production server we have set open_basedir and follow location is not working;/ So I found some workaround of this issue. I created function that provides similar functionality for CURLOPT_FOLLOWLOCATION option. It's working when you are in safe_mode or you have open_basedir set.

CURLOPT_FOLLOWLOCATION fix

function curl_follow_exec($ch)
{
    curl_setopt($ch, CURLOPT_HEADER, true);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    $data = curl_exec($ch);
    $http_code = curl_getinfo($ch, CURLINFO_HTTP_CODE);

    if ($http_code == 301 || $http_code == 302) {
        preg_match('/(Location:|URI:)(.*?)\n/', $data, $matches);
        if (isset($matches[2])) {
            $redirect_url = trim($matches[2]);
            if ($redirect_url !== '') {
                curl_setopt($ch, CURLOPT_URL, $redirect_url);
                return curl_follow_exec($ch);
            }
        }
    }
    return $data;
}

It just check if response code is 301 or 302, getting the location URL from headers and perform another cURL request for location URL. It is recurrence function and it will end when there's no redirection left. You can always add some counter and check if there's no more than 10 redirections for example. Just not to get into infinite loop with redirections.

Real-life usage

Example use here for grabbing profile image from facebook

public function getUserPicture($uid)
{
    $url = 'http://graph.facebook.com/' . $uid . '/picture?type=large';
    $ch = curl_init($url);
    $image = curl_follow_exec($ch);
    curl_close($ch);
    return $image;
}

$uid is facebook user id, you can get it for example from facebook api, when user will authorize your website for such informations. Function curl_follow_exec is taking one parameter which is curl handle. You can create curl handle with curl_init, set any option as you like and call curl_follow_exec instead of curl_exec.

You can read more about cURL, CURLOPT_FOLLOWLOCATION and other useful options in php manual here: http://php.net/manual/en/book.curl.php

Database backup and restore (export and import) with mysqldump

mysql dump - tool for database backup and restoreI want to present you very useful tool, which not every developer uses: mysqldump - application for database backups.

It's very useful tool when you want to export (backup) your database. Of course you can use well known phpMyAdmin, but when it comes to export very large database it becomes pretty useless (long export time, timeouts, browser freezings, etc...)

So lets use mysqldump. It should be installed with mysql installation, so you don't have to bother finding it, extra downloads etc. By default its in your mysql_installation_directory/bin/ If you have it on your PATH list, simply type in console mysqldump.

Database backup

Ok, lets look at basic example:

mysqldump -u user -ppassword -h host database_name > database_dump_file.sql

Where:

  • user - database user
  • password - database user password (there's no space between -p and your password!)
  • host - host where your database is located (by default it's localhost, so this parameter is optionally, use it when you want to export database from external host)
  • database_name - database name you want to backup
  • database_dump_file.sql - file with exported data

Practice:

mysqldump -u astaz3l -psupersecretpassword1234 wp_database > 2013_06_18.sql

After some time (depends on the database size) in 2013_06_18.sql file we will have complete database dump from wp_database. I didn't use -h parameter as it's localhost.

Except of -u, -p, -h we can use more parameters.

  • --no-data will export only structures(tables, fields, etc...) without data
  • --no-create-info will export only data without structure. Be careful when you will use this parameter. You must be sure, that you have exactly the same structure in database when you want to import such dump.
  • --all-databases pretty useful option when you want to backup all databases

More options you can find in mysqldump manual here:
http://dev.mysql.com/doc/refman/5.1/en/mysqldump.html

Database restore

Ok, now we know how to export database. How to import dumped database? Using mysql command.

mysql -u user -ppassword -h host database_name < database_dump_file.sql

It's very similar to making database backup, isn't it? Only difference is tool name and < sing. Parameters are exactly the same as during export. Real life usage:

mysql -u astaz3l -psupersecretpassword1234 wp_database < 2013_06_18.sql

It is possible to restore database with mysqldump file and phpMyAdmin. Simply choose import tab from phpMyAdmin and use exported file.

WordPress and good WordPress plugins (tech part about this blog)

WordPress and WordPress pluginsOK, lets learn something more about this site(blog) which is run on Worpress with couple WordPress plugins.

At the beginning I thought that I will write it completely from scratch with ZF. But hmmm, when I realize how many things I should create and time I should put into this project I decided for ready solution. If it's a blog, solution is pretty obvious - WordPress. I didn't use it for about 2 years, so I think it might be nice to back to some old solutions.

I downloaded WordPress 3.5.1 from wordpress.org page. Installation as always was very simple, after uploading whole stuff to the server and launching url of the blog we will find simple Step by Step installation. If you know a little bit about web, it shouldn't make you any troubles. After installation it's all about clicking through the configuration pages and set options which suits you best. I used default theme, it's pretty nice, has responsive version (where I found one, or two bugs already, i will fix them later).

OK, so thats it! We can start writing posts, create about me page etc:P W have fully functional blog in 10 minutes. But hey! WordPress has many plugins which increase WP power. So I decided to look around a little bit for some good wordpress plugins and I found really useful stuff. Here are the list of WordPress plugins that are used in this blog:

Akismet

Used by millions, Akismet is quite possibly the best way in the world to protect your blog from comment and trackback spam. It keeps your site protected from spam even while you sleep.

Its bundled with the WordPress installation but it's disabled by default. In order to make it active You need the API key (which is free) from Akismet website

Download link: http://wordpress.org/plugins/akismet/

Crayon Syntax Highlighter

Syntax Highlighter supporting multiple languages, themes, fonts, highlighting from a URL, local file or post text.

Very handful WordPress plugin for syntax highlighting. Tons of options and supported languages. A must have for any developer

Download link: http://wordpress.org/plugins/crayon-syntax-highlighter/

Sociable

Automatically add links on your posts, pages and RSS feed to your favorite social bookmarking sites.

If you want to have the blog it won't be good if you won't place share/like buttons on your page.

Download link: http://wordpress.org/plugins/sociable/

W3 Total Cache

Easy Web Performance Optimization (WPO) using caching: browser, page, object, database, minify and content delivery network support.

I tried Hyper Cache with WP Minify previously but I couldn't make it work properly on my WordPress installation so I changed it for W3 Total Cache - I think it was good choice, for now everything is working very nice. Even if you do not expect large traffic on your website it's good to have tool like that installed. It will speed up loading time of your website. Faster loading time = more satisfied user:) Very good WordPress plugin!

Download link: http://wordpress.org/plugins/w3-total-cache/

WordPress SEO by Yoast

The first true all-in-one SEO solution for WordPress, including on-page content analysis, XML sitemaps and much more.

Nice WordPress plugin for SEO, when you write post it shows you the SEO statistics and give you advices for optimization.

Download link: http://wordpress.org/plugins/wordpress-seo/

Thats all WordPress plugins I installed on my fresh installation. I will update this post when I will add some new plugins:) Do you know any good plugin for WordPress? Leave info in comments below:)

Hello world!

wallpaper-2372353Hello everybody!

I've started this blog because sometimes I like to write something else than code. If you are interested what technologies I'm using visit my about me page.

At the beginning I thought that I'll be writing here only tech articles. Sometimes I use code which is pretty nice, useful etc. Few months after I would like to use this code again but I don't have it on my second computer for instance;/ So I decided to create some mechanism for storing my codes, something like snippets. Yesss I know, there are plenty mechanisms like that, I could use one of them. But hey! Why only I should have access to it? Maybe someone else will find it useful. So I decide to create the blog:) In my next post I will tell you what solution I used for this blog.

You will find here probably something more than just code snippets, some posts about my personal projects, posts about my world and posts about nothing:P

Yeah, we will see what will happen here xD

Our services: