A web developer's blog. PHP, MySQL, CakePHP, Zend Framework, Wordpress, Code Igniter, Django, Python, CSS, Javascript, jQuery, Knockout.js, and other web development topics.

Some useful Knockout.JS examples from my JSFiddle

I am learning Knockout.js

Accessing an observable array outside the foreach loop from the HTML
http://jsfiddle.net/wenbert/MEKLN/

Setting a default / selected option in a Select box
http://jsfiddle.net/wenbert/ZpGeS/

Working with child models
http://jsfiddle.net/wenbert/Ev8H6/

Thanks to the guys at Stackoverflow and #javascript in Freenode for replying to my questions. RP Niemeyer from Knockmeout.net, nemesv and tyrsius.

Posted in Uncategorized | Leave a comment

CakePHP 2.x: CSV File download from a database query

Here is a quick way to output/stream/download a CSV file from your database using CakePHP.

For simplicity, I have placed everything in the controller. Not good practice but it quickly does the job.

<?php
class UsersController extends AppController {
 
// ...snip...
// the rest of your code here
 
    public function downloadentries() {
 
        if($this->request->is('post')) {
            $this->loadModel('Member');
            $filename = "myfile.csv";
            $start_date = '2012-10-08 00:00:00';
            $end_date = '2012-10-08 23:59:59';
            $results = $this->Member->find('all', array(
                        'conditions' => array('Member.created >=' => $start_date, 
                                        'Member.created <=' => $end_date)
                    ));
 
            $csv_file = fopen('php://output', 'w');
 
            header('Content-type: application/csv');
            header('Content-Disposition: attachment; filename="'.$filename.'"');
 
            $header_row = array("id", "name", "email");
 
            fputcsv($csv_file,$header_row,',','"');
            foreach($results AS $result) {
                $row = array(
                $result['Member']['id'],
                $result['Member']['name'],
                $result['Member']['email']
                );
 
                fputcsv($csv_file,$row,',','"');
            }
            fclose($csv_file);
        }
        $this->layout = false;
        $this->render(false);
        return false;
    }
 
// ... more code here...
}

You might be also interested in outputting it as an Excel File: Zend Framework: View File downloaded as Excel File. Different framework but the same idea.

Sources: A, B

Posted in Uncategorized | Tagged , , | 3 Comments

CouchDB and PHP Web Development Beginner’s Guide

CouchDB and PHP Web Development Beginner’s Guide from Packt Publishing has been released. I was a technical reviewer for the book. The book has been released more than a month ago but I was not able to announce it here. The reason: I moved to New Zealand.

I did not have a lot of experience with CouchDB – so reviewing the book gave me a chance to know it better. The book is targeted for beginners which is quite good because it guides you through the installation process, basic usage, and what CouchDB is all about. It makes sure that you absorb the good stuff before moving on to the more advanced features in CouchDB. I really appreciated this.

Another bonus is that you get to “write” and conceptualize your own basic PHP Framework therefore the code is organized and very easy to work with.

Things I liked about the book:

  • teaches you the basic stuff
  • makes you use Git
  • you get to write your own very PHP framework – if you are a new, then moving to other MVC Frameworks will be easy
  • has chapters about deploying your application – security, replication, etc.

You can grab the book right here.

Posted in Uncategorized | 2 Comments

WordPress: Custom post filters for Search

If you want to customize the query when doing a search in WordPress – when meta_queries are not enough.

The custom “WHERE” part of the query

function custom_where($where,$query) {
  global $wpdb;
 
  $new_where = " /*my new where*/ $wpdb->postmeta.meta_value LIKE '%".get_search_query()."%'";
  if (empty($where))
    $where = $new_where;
  else
    $where = "{$where} /*OR*/  OR {$new_where}";
 
  return $where;
}

The “DISTINCT” part

function search_distinct() {
  return "DISTINCT";
}

The custom “JOIN”

function custom_join($join) {
  global $wp_query, $wpdb;
  $join .= "INNER JOIN $wpdb->postmeta ON $wpdb->posts.ID = $wpdb->postmeta.post_id ";
  return $join;
}

Putting them all up for the “pre_get_posts”

function filter_search($query) {
    if ($query->is_search) {
      $query->set('post_type', array('post', 'recipes'));
      add_filter('posts_where','custom_where');
      add_filter('posts_join', 'custom_join');
      add_filter('posts_distinct', 'search_distinct');
    }
    //var_dump($query);
    return $query;
};
 
add_filter('pre_get_posts', 'filter_search');
Posted in Uncategorized | Leave a comment

Using Javascript to Set the Image Width in Images with Responsive Layouts

The scenario

Let’s say you have an image 600 pixels wide, in responsive layouts, you have to set the image width to 100% – or else it will not “adjust” to changes in the window size.

On your desktop, the width of your window will be greater than 600 pixels, so the image will be stretched and will loose it’s quality – it will become pixelated/blurry. On your mobile device, when the screen is less than 600 pixels wide, a horizontal scroll bar will appear – you loose the responsiveness of your layout.

The work-around

To go around this problem, I would want to set the image width to 100% only when the window width is lesser than the image width. If the image width is lesser than window width, just display the image in it’s original size.

The code

<script language="javascript" type="text/javascript">
    function getOriginalWidthOfImg(img_element) {
        var t = new Image();
        t.src = (img_element.getAttribute ? img_element.getAttribute("src") : false) || img_element.src;
        return t.width;
    }
 
    function responsive_images () { 
        $(".responsive_img").each(function() {
            if(parseInt(getOriginalWidthOfImg(this)) >= parseInt($(window).width())) {
                $(this).attr("width","100%");
            } else {
                $(this).removeAttr("width");
            }
        });
    }
 
    $(window).load(function() {
        responsive_images();
        $(window).resize(function() {
            responsive_images();
        });
    });
 
</script>

Note: You will need jQuery.

Credits:
FDisk’s answer in Stackoverflow: http://stackoverflow.com/a/3192577/66767

Posted in Uncategorized | 3 Comments

Infinite Scrolling with WordPress

I got the chance to implement this in WordPress.

The first step, install the JSON API plugin for WordPress. It can be downloaded here: http://wordpress.org/extend/plugins/json-api/ or just search “JSON API” in your WP-Admin plugins section.

This plugin is really neat because it gives us a JSON response for any WordPress press by just appending ?json=1 at the URL. For example if I load this URL with the plugin installed: http://localhost/?json=1 I get a response in JSON containing the Posts in my frontpage.

{
  status: "ok",
  count: 2,
  count_total: 24,
  pages: 12,
  posts: [
    {<snipped - will contain the title, excerpt, date, etc.>},
    {<snipped - will contain the title, excerpt, date, etc.>}
  ]
}

In your template you just need to setup a container for the dynamically loaded items and a “loading” gif image.

<div id="ajax_content"></div>
<div class="row" id="loader">
  <div class="span12" style="text-align: center; margin-bottom: 20px;">
    <img src="<?php bloginfo('stylesheet_directory'); ?>/images/ajax-loader.gif" alt="" />
  </div>
</div>

The javascript part is pretty straight forward. The unlocked variable is pretty important since it prevents duplicate calls to the AJAX request. This is only quick way I got around that problem (duplicate calls).

<script language="javascript" type="text/javascript">
  page_number = 2; //starting with what page number? 
  template_directory = '<?php echo get_bloginfo("template_directory") ?>';
  unlocked = true; //this is to make sure we only load once
  $(window).scroll(function() {
    if($(window).scrollTop() + $(window).height() > $(document).height() - 100) {
      $("#loader").show();
      if (unlocked) {
        unlocked = false;
        $.ajax({
          type: "GET",
          url: "<?php echo get_bloginfo('url'); ?>/page/"+page_number+"",
          data: "json=1",
          success: function(data){
            console.log(data)
            page_number++;
            if (page_number <= data.pages) {
                $.each(data.posts, function(key, val) {
                  console.log(key+" > "+val.title)
                  $("#ajax_content").append(
                    '<div class="row">'+
                    '<div class="span12">'+
                    '<h2>'+
                    '<a href="'+val.url+'" rel="bookmark" title="Permanent Link to '+val.title+'">'+
                    val.title+
                    '</a>'+
                    '<p>'+val.excerpt+'</p>'+
                    '</div>'+
                    '</div>'
                  );
                });
            }
            $("#loader").hide();
            unlocked = true;
          }
        });
      }
    }
  });
</script>

Credits:
Stackoverflow
Ajax Load

Posted in Uncategorized | Leave a comment

Moving to Auckland, New Zealand. Looking for a job.

Hi Everyone,

My wife and I are moving to Auckland, New Zealand. I have Work-to-Resident Visa. Our departure will be on the May 13, 2012.

If you are looking for a web developer then send me an email. You can download my CV here.

I am open to working remotely. Then we can talk once I get to New Zealand.

** If you know anyone who is looking for someone with my skills, then please recommend me.

Regards,
Wenbert

Posted in Uncategorized | 2 Comments

Ruby on Rails: Multiple file attachments with Carrierwave and Nested_form

First, I would like to thank Luca for this post.

Add in Gemfile

gem "nested_form", :git => 'https://github.com/ryanb/nested_form.git'

Then run

bundle install

and

rails g nested_form:install

In my “parent” model:

class Allergy < ActiveRecord::Base
  validates :name, :presence => true
  has_many :attachments, :dependent => :destroy
  accepts_nested_attributes_for :attachments
end

In my “child” model:

class Attachment < ActiveRecord::Base
  belongs_to :allergy, :polymorphic => true #add polymorphic
  mount_uploader :attachment, AttachmentUploader
end

In my views:

...
<%= nested_form_for [@patient, @allergy], :html => {:multipart => true} do |f| %> 
    <%= render :partial => "fields", :locals => {:f => f} %>
<% end %>
...

and in the partial I have this:

<%= f.fields_for :attachments do |attachment_form|  %>
  <div class="clearfix">
    <%= attachment_form.label :desc %>
    <%= attachment_form.text_field :desc %>
    <%= attachment_form.label :attachment %>
    <%= attachment_form.file_field :attachment %>
    <%= attachment_form.link_to_remove "Remove this attachment" %>
  </div>
<% end %>
<%= f.link_to_add "Add attachment", :attachments %>

And to save in the controller, I have something like this:

def create
...
  @patient = Patient.find(params[:patient_id])
  if @allergy = @patient.allergies.create(params[:allergy])
    # success
  else
    # error handling
  end
end

I might have missed something, but if you have comments, suggestions, and corrections do not hesitate to post them below. I am also very new to Ruby on Rails.

Might be different from what you have but this doc was useful.

Posted in Uncategorized | Leave a comment

Unable to update / upgrade anything in WordPress using Auto-Update

You are unable to upgrade automatically your WordPress installation. You are also not able to update your plugins. You have also tried everything to make your connection settings correct and it still does not work.

The reason: Your PHP scripts does not have the permission to write.

The solution: Install suPHP

$ apt-get install libapache2-mod-suphp

Add this in your Apache conf:

suPHP_Engine on

Then:

$ a2dismod php5
$ /etc/init.d/apache2 restart

CHOWN and CHGRP your home directory

$ chmod -R wenbert /home/wenbert
$ chgrp -R wenbert /home/wenbert

Resources: http://www.suphp.org/DocumentationView.html?file=apache/INSTALL

FYI: I am on Ubuntu.

Posted in Uncategorized | Tagged , , | Leave a comment

Ruby on Rails: execjs Javascript runtime error when executing “rails server”

My schedule right now is not very tight and I have a couple of hours free almost everyday. So instead of playing Skyrim, I am learning Ruby on Rails.

I am using RVM (http://beginrescueend.com/) on Ubuntu Ubuntu 10.04 LTS (Lucid Lynx).

Here is the error I get when I try to run “rails server”:

wenbert@ubuntu:~/projects/rails/depot$ rails server
/home/wenbert/.rvm/gems/ruby-1.9.2-p290/gems/execjs-1.2.12/lib/execjs/runtimes.rb:47:in `autodetect': Could not find a JavaScript runtime. See https://github.com/sstephenson/execjs for a list of available runtimes. (ExecJS::RuntimeUnavailable)
	from /home/wenbert/.rvm/gems/ruby-1.9.2-p290/gems/execjs-1.2.12/lib/execjs.rb:5:in `<module:ExecJS>'
	from /home/wenbert/.rvm/gems/ruby-1.9.2-p290/gems/execjs-1.2.12/lib/execjs.rb:4:in `<top (required)>'
	from /home/wenbert/.rvm/gems/ruby-1.9.2-p290/gems/coffee-script-2.2.0/lib/coffee_script.rb:1:in `require'
	from /home/wenbert/.rvm/gems/ruby-1.9.2-p290/gems/coffee-script-2.2.0/lib/coffee_script.rb:1:in `<top (required)>'
	from /home/wenbert/.rvm/gems/ruby-1.9.2-p290/gems/coffee-script-2.2.0/lib/coffee-script.rb:1:in `require'
	from /home/wenbert/.rvm/gems/ruby-1.9.2-p290/gems/coffee-script-2.2.0/lib/coffee-script.rb:1:in `<top (required)>'
	from /home/wenbert/.rvm/gems/ruby-1.9.2-p290/gems/coffee-rails-3.1.1/lib/coffee-rails.rb:1:in `require'
	from /home/wenber

A lot of people have already experienced this error. There is a popular thread for this in Stackoverflow – here. The Original Poster of the thread selected the this answer:

I’m on Ubuntu 11.04. Had similar issues. Installing node.js fixed this for me

https://github.com/joyent/node/wiki/Installing-Node.js-via-package-manager

But I think the more appropriate answer is the one by vincent jacquel in this thread.

The Fix

  1. Open the Gemfile
  2. Add these lines:
    gem 'execjs'
    gem 'therubyracer'
  3. Save.
  4. Then run this command: $> bundle after
Posted in Uncategorized | 4 Comments