Sunday, June 16, 2013

PHP : Excel Reader

Reading excel sheets now a days is not that big challenge, but reading it with very advanced formulas is definitely a very big challenge. One of team really spent a very pressured day to work on this functionality.

We used PHPExcel but was not reading values from other sub-sheet while performing getCalculatedValue(). Everything else was working fine. Like dynamically adding new values and generating the excel. After opening the new excel it worked like the original with new values. But the main functionality which we wanted, was getCalculatedValue() to display the calculations on web page.

After checking other plugins we found one more excel reader at devzone.zend.com. Tried with our excel sheet which worked like a charm.

Really useful for getting advanced formulas calculated values. There is also a excel writer but I didn't check it yet.
The only limitation to this plugin is that it do not work with xlsx file.

Thursday, May 30, 2013

CakePHP = Rails Framework

As I said in previous posts I really miss rails framework while working for PHP web applications. Just looking around the best sites on rails I found that CakePHP has a similar framework like rails.

Was really excited to get hands on it. Downloaded the latest version of the framework and started the application. But crashed with several warnings like 'Warning: _cake_core_ cache was unable to write...'

After reading warnings and checking around for solution, found, that need to provide writable permissions to tmp in app folder chmod -R 777 app/tmp which really helped for starting the project smoothly. Also found the answer which is helpful for other errors.

Until now I found that it contains functions similar to rails like beforeFilter() and so on, although I am not yet familiar with this framework. But it contains many function which I tried to build in my framework like render or helpers.

I am really going to love this if it works like rails, and will have no complaints about PHP.

Thursday, May 16, 2013

QA : 3 : How to implement the twitter authentication in rails 3.2?

Question from Bala Chandar :

How to implement the twitter authentication in rails 3.2?

Answer :

There is a gem available for twitter authentication oauth-plugin by Pelle Braendgaard

Please check the link Twitter Authentication Settings.

Friday, April 12, 2013

Collection : Javascript : Using select tags for date selection

Now a days generally most of sites use calendar dialog boxes for selecting a date in forms. We get all functionality for that including leap years and 30 or 31 days depending on the month. But how can we get these all when we are using simple drop downs or select is the question. Well we can use javascript to validate the fields.
In this post we will use jquery for validating 3 dropdowns which are year, month and date. As I was working on PHP the example will hold PHP code.

In this example consider that we are working on employee joining form and we want to add a joining date.
In html
<div id="joiningDate">
  <?php 
    $joining_date = select_tag("employees[joining_date][month]", unserialize(MONTHS), date('F'), array('class' => 'month'));
    $joining_date .= select_tag("employees[joining_date][date]", unserialize(DAYS), date('j'), array(class' => 'date'));
    $joining_date .= select_tag("employees[joining_date][year]", array("2012", "2013", "2014", "2015", '2016', '2017'), date('Y'), array('class' => 'year'));
    echo $joining_date;
  ?>
</div>
Note : For select_tag please check Collection : PHP : select_tag

Define some constants for long arrays.
Constants
defined('MONTHS') or define("MONTHS", serialize(array('January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December')));
defined('DAYS') or define('DAYS', serialize(array('01', '02', '03', '04', '05', '06', '07', '08', '09', '10', '11', '12', '13', '14', '15', '16', '17', '18', '19', '20', '21', '22', '23', '24', '25', '26', '27', '28', '29', '30', '31')));
Finally the javascript function which will actually play the magic in html. Check the comments for explanation. In Javascript file
$(document).ready(function(){
  validateDateFields('#joiningDate');
});

function validateDateFields(divID){
  // Jquery objects of date and month fields in new function
  var dateField = $(divID).find('select.date');
  var monthField = $(divID).find('select.month');

  // Months hash for adding or removing the options tags 
  var monthsHash = {
    'January' : 1, 
    'February' : 2, 
    'March' : 3, 
    'April' : 4, 
    'May' : 5, 
    'June' : 6, 
    'July' : 7, 
    'August' : 8, 
    'September' : 9, 
    'October' : 10, 
    'November' : 11, 
    'December' : 12
  };
  // Months with 31 days
  var fullMonth = [1, 3, 5, 7, 8, 10, 12];
  
  // Current values of the fields
  var dateVal = dateField.val();
  var monthVal = monthField.val();
  var yearVal = $(divID).find('select.year').val();
  
  // Check current year if leap year
  var isLeap = new Date(yearVal, 1, 29).getMonth() == 1;
  // Date field child node with options 29, 30 and 31
  var dateOption29 = dateField.children('option[value=29]');
  var dateOption30 = dateField.children('option[value=30]');
  var dateOption31 = dateField.children('option[value=31]');
  // defining other variable 
  var appendOptions;
    
  if(monthsHash[monthVal]==2){
    // First : If selected month in 2 or February
    if(isLeap){
      // If the selected year is leap year
      if(dateOption29.length == 0){
        // If date field child nodes do not have any option with value 29
        dateField.append('<option value=29>29</option>');        
      }
    }else{
      // If its not a leap year remove date field child node option with value 29
      dateOption29.remove();
    }
    // In month 2 or february by default remove date field child options with value 30 and 31
    dateOption30.remove();
    dateOption31.remove();
  }else if($.inArray(monthsHash[monthVal], fullMonth) > -1){
    // If the selected month is of 31 days 
    if(dateOption31.length == 0){
      // If option with value 31 do not exist 
      if(dateOption29.length == 0){
        // If option with value 29 do not exist 
        appendOptions += '<option value=29>29</option> <option value=30>30</option>';
      }else if(dateOption30.length == 0){
        // If option with value 30 do not exist 
        appendOptions += '<option value=30>30</option>';
      }
      appendOptions += '<option value=31>31</option>';
      // append options which do not exist in date field child nodes
      dateField.append(appendOptions);
    }
  }else{
    // If the selected month is of 30 days 
    if(dateOption29.length == 0){
      // If option with value 29 do not exist 
      dateField.append('<option value=29>29</option> <option value=30>30</option>');
    }else if(dateOption30.length == 0){
      // If option with value 30 do not exist 
      dateField.append('<option value=30>30</option>');
    }else if(dateOption31.length > 0){
      // If option with value 31 exist
      dateOption31.remove();
    }
  }
  
  // Add other code for updating any values here.
}

Thursday, March 28, 2013

PHP : Apple Push Notification (APN)

Hope you have read my previous post for Rails 3 : APN on Rails in which I tried apn_on_rails gem for sending notification to apple devices. I have also added the link for ManiacDev.Com in which you will get the steps for certification creation which are the most important steps for notifications.

Now for sending notification in PHP there is a great example available at raywenderlich.com : Apple Push Notification Services Tutorial: Part 1/2. You can download the example file at from given link in the post.



This is a PHP sample code. Just change the deviceToken, passphrase and message variables. Make changes as per your requirement. But again I faced some certification errors which were : ssl_connect returned=1 errno=0 state=sslv3 read finished a sslv3 alert certificate unknown and Neither PUB key nor PRIV key:: nested asn1 error. Nothing else got the wrong certificate generated. Just get the required certificate and you are good to go.
I really loved it.

Tuesday, March 5, 2013

Rails : Code : Split Records

I was very much impressed when I saw the split entry functionality in time-sheet project we were using. I wanted to try out same in ROR. But I will also try this out in PHP now. First we will look at ROR code.

Assume that we are creating a time-sheet project and we need to split the duration and considering, we already have the rails project with authentication, and now we generate a new section 'Time Records', which will store the records of users with duration.
I am running scaffold so we will have all views, controller and model.
 rails g scaffold time_records description:text duration:float parent_id:integer


Run migration to add table in database.
 rake db:migrate
Now we will add new record



This is a basic setup what we need till now. Once this base is complete we will start with actual requirement. Now first we need to add a anchor tag (link) with which the functionality will work. SO I have added it in index page.



In this example I am using javascript function for ajax call but it is not complusory, we can directly use send the user to the form page with out javascript. So I am using onclick attribute for calling a function.
<%= link_to 'Split', '#', :onClick => "split_duration_for_entry('split_#{time_record.id}', #{time_record.id})" %>
In that function
/* this is for spliting the duration */
function split_duration_for_entry( div, id ){
  var divid = "#"+div
  var classes = jQuery(".split_box");

  jQuery(classes).each(function(){
    var thisid = $(this).parent('td').attr('id')
    var v = jQuery("#"+thisid).next().val();
    jQuery("#"+thisid).html("<a href='#' onClick=\"split_duration_for_entry('"+thisid+"', "+id+")\">Split</a>")
  });

  actual_duration = $('#split_'+id).prev('td').html();
  jQuery.ajax({
    type: 'GET',
    url: '/time_records/split_entries_div',
    data:{'record_id' : id, 'actual_duration': actual_duration},
    success: function(transform){
      jQuery(divid).html(transform);
    }
  });
}

So this function will
  • Hide opened split duration divs if open.
  • Send the parameters(id and duration) to split_entries_div action in our controller.
  • Once the action is called display the partial with data and links.

In controller
def split_entries_div
  id = params[:record_id].to_i
  time_record = TimeRecord.find(id)
  render partial: "split_entries", locals: {record_id: id, old_duration: time_record.duration.to_f}, layout: false
end 
So here comes the partial.
  
<div class="split_box">
  <div>
    <%= hidden_field_tag "actual_duration#{record_id}", params[:actual_duration] %>
    <%= text_field_tag "old_duration_#{record_id}", params[:actual_duration], size: 5 %>
    <%= text_field_tag "new_duration_#{record_id}", 0, size: 5 %>
  </div>
  <div>
    <%= link_to 'Split', "#this", onClick: "split_entries(this, #{record_id})" %>
    <%= link_to "Cancel", "#this", onClick: "cancel_split_entry(this, #{record_id})" %>
  </div>
</div>
In CSS
.split_box{
  background: none repeat scroll 0 0 #EFEFEF;
  border: 4px solid #CCCCCC;
  width: 100px;
}

In this partial we will have
  • 2 main text fields which will contain the old duration for updating the original record and new duration for which we will be creating a new record.
  • 1 hidden field to keep the original duration so if the validation is called then we can again store the original duration value to old duration field.
  • 2 anchor tags for calling actual functionality and canceling the div poped up.



First the main functionality. Actual spliting/ updating the entry will be performed if the user clicks the split link. On which 'split_entries' function is called by passing record's id.

function split_entries( id ){
  var newrecrd;
  var new_record_val = jQuery("#new_duration_"+id).val();
  var old_record_val = jQuery("#old_duration_"+id).val();
  
  var actual = $("#actual_duration"+id).val();
  var total = parseFloat(old_record_val) + parseFloat(new_record_val);
  
  if(parseFloat(actual) < total ) {
    alert("Total duration for OLD and New records can not be greater than original value");
    jQuery("#old_duration_"+id).val(actual);
    jQuery("#new_duration_"+id).val(0);
    return false; 
  }else if(parseFloat(old_record_val) < 24){
    if(new_record_val==0 || new_record_val==""){
      newrecrd = false
    }else{
      newrecrd = true
    }

    cancel_split_entry(id);

    jQuery.ajax({
      type: 'GET',
      url: '/time_records/split_entries',
      data:{
        'newrecrd' : newrecrd,
        'old_id' : id,
        'old_duration': parseFloat(old_record_val).toFixed(2),
        'new_record_val' : parseFloat(new_record_val).toFixed(2)
      },
      success: function(transport){
        window.location.reload();
      }
    });
  }else {
    alert("Duration can not be greater than 24 hrs. Enter valid duration");
    return false;
  }
}

I have added some validations to this functionality
  • Duration can not be greater than 24 hours OR
  • The total of both value can not be greater that the original duration
We can just remove/ modify these validation as per our requirement

Other than that
  • If it passes the validation it will first check if the new duration value should not be blank or equal to 0. This will set true or false to local variable 'newrecrd' which will be passes to the action as parameter via ajax.
  • Original record is will be passes and old_id.
  • Both new duration and old duration will be passed to the action.
  
# split duration
  def split_entries
    @time_record = TimeRecord.find(params[:old_id].to_i)
    description = @time_record.description
    @time_record.update_attributes(description: description, duration: params[:old_duration])
    if params[:newrecrd]=='true'
      TimeRecord.create(description: description, duration: params[:new_record_val], parent_id: @time_record.id)
    end
    redirect_to :back
  end
In which get the original record and update the duration
  • if params[:newrecrd] is true then create a new record with new duration value.
And now in routes add
resources :time_records do 
  collection do 
    get 'split_entries'
    get 'split_entries_div'
  end
end



Once the set up is done restart the application and check the output


Get the code at Github : Split-Records

Friday, March 1, 2013

Collection : Dabblet

There are many tools now a days to check your HTML and CSS code directly in browser for quick development. Tools like Firebug or inbuilt developer tools in browsers helps a lot, to check instant changes and don't have to wait for loading the page each time for small changes.

Dabblet is also a very useful tool to develop and test your CSS and HTML code.



This supports the modern versions of browsers like chrome, firefox and safari. But do not support IE.



You can get more information on dabbel help page. Advantage of this is that you don't have to keep the file on local machine. You can just save it on the gist.github.com as anonymous or you can also sign in with your account for storing the changes.




The output can be viewed at http://dabblet.com/gist/5062815 or you can just view the code at github.com/anonymous/5062815. Also you can view the whole page result at result.dabblet.com.



Now as I have mentioned earlier that dabble do not support IE but you can just check the output after storing the changes to github.

Friday, February 22, 2013

PHP : MVC : Framework

I really missed rails framework and available helpers a lot while working on PHP.
But I really learned a lot while finding the similar functionalities in PHP.
I tried the some of the available PHP frameworks but didn't find anything like rails.

So I started to define helpers and functions for my current PHP project.
Currently it's not complete but working with minor bugs.
Bugs like
  If I try to call view without .php extension it works fine, but with .php extension it crashes.

Still missing the actual flow of MVC (model, views and controller)(need to work on it).

Folder structure for this application is as follows:
  
app    
    |- assets    
        |- fonts
        |- images
        |- javascripts
        |- stylesheets
    |- classes
    |- helpers
    |- views
        |- Folder
  config
    |- config.php
    |- constants.php
    |- database.php
    |- path_includes.php
    |- routes.php
  docs
  includes
    |- classes
        |- application.class.php
    |- helpers
        |- common_helper.php
    |- php
        |- active_queries.php
        |- authentication.php
        |- base.php
        |- structure.php
        |- word_plurals.php
  lib
  index.php
  login.php
  logout.php
  navigation.php
  session_settings.php
  signin.php
  ReadMe.txt
  
Need to do lots of changes.
I have uploaded the code to GitHub. If anyone can help me to solve the current bug that will be a great help.

Monday, January 14, 2013

PHP : API : Documentation

Documentation is very necessary for every project. I usually add comments for every function in my project but getting the whole summary to one place was important.

In rails I knew how to do it but in php?
I came across apigen for php project 'professional API documentation tool'.
Really great to see the result. Loved it.

So we need to download the pack from apigen.org



Extract it to required path and then follow the steps given at blogs.oracle.com. Nice post.

Thats it and we are ready with the api for our projects.

Tuesday, December 25, 2012

PHP : mod_rewrite services

Experience working with PHP is really good. But really missed the way rails for handling urls dynamically.
Really feeling nice when I found the way to add such method for dynamic urls.
Just need to use mod_rewrite in .htaccess file for the respective project.

In the beginning didn't work as per the requirement.

After some research found the post enable-mod_rewrite-in-a-ubuntu-server which helped a lot for starting the mod_rewrite services.

By default it showed that mod_rewrite services are running but need some changes in the files which are as below.

Just need to run
sudo gedit /etc/apache2/sites-enabled/000-default
and in <Directory /> and <Directory /var/www/> section change
AllowOverride None
to
AllowOverride All
And then just
sudo /etc/init.d/apache2 restart