jQuery plugin – split MySql date format value of a form element into select form elements

Here is a simple and quick jQuery plugin that will split the MySql date format values of an form element into select form elements.

Html element:


Call the plugin:

$(function() {
    $('#birth_date').birthDate();
});

And the plugin:

/**
 * Simple plugin that converts an hidden html element
 * that has a MySql date format value into select elements
 *
 * @author Calin Rada 
 */
$.fn.birthDate = function( options ) {

    if($(this).length == 0) {
        return false;
    }

    var settings = $.extend({
        dateFormat: "d-m-Y"
    }, options );

    var currentDate = new Date();
    var minYear = currentDate.getFullYear() - 110;

    $('').insertAfter($(this));

    if($('#birthDatePlugin').length > 0) {

        var dates = $('#birth_date').val().split('-');
        var year  = dates[0];
        var month = dates[1];
        var day   = dates[2];

        var content      = '';
        var yearContent  = '';
        var dayContent   = '';

        for (i=minYear; i<=currentDate.getFullYear(); i++) {
            if(i == year) {
                yearContent += '';
            } else {
                yearContent += '';
            }
        }
        yearContent += endSelect;

        for (i=1; i<=12; i++) {
            if(i == month) {
                monthContent += '';
            } else {
                monthContent += '';
            }
        }
        monthContent += endSelect;

        for (i=1; i<=31; i++) {
            if(i == day) {
                dayContent += '';
            } else {
                dayContent += '';
            }
        }
        dayContent += endSelect;

        switch(settings.dateFormat) {
            case 'd-m-Y':
                content = '
' + dayContent + '
' + monthContent + '
' + yearContent + '
'; break; } $('#birthDatePlugin').html(content); $('#birth_year, #birth_day, #birth_month').on('change', function(){ var newVal = $('#birth_year').val()+'-'+$('#birth_month').val()+'-'+$('#birth_day').val(); $('#birth_date').val(newVal); }) } }

And the result:

If this helped you, i’m glad 🙂

Using Twig with Phalcon PHP

You might wonder why using Twig with Phalcon PHP and not using Volt. Well, i had 2 main reasons:

1. I have been using Twig for the last 2 years and it’s available as a C extension also.
2. Using Volt it’s almost exactly the same thing, but for now it seems that Volt is not so stable – mostly because of the view renderer. I had a lot of problems while trying to render Volt templates (Phalcon 1.3.0). Anyway, when it will be stable, i will use Volt for sure. So, if you read this while you have a stable Volt and it is not mandatory to use Twig, just use Volt.

Using Twig with Phalcon PHP

Here is what you have to do:

1. Download Twig
2. Register it in your bootstrap

require "YOUR_PATH_TO_TWIG/Autoloader.php";
Twig_Autoloader::register();

3. Download Twig View from Incubator and register it to your namespace.

4. Edit your service file and add a twig service to DI

$di['twigService'] = function($view, $di) {
    Namespace\To\Twig\View::setOptions(array(
        'debug'               => true,
        'charset'             => 'UTF-8',
        'base_template_class' => 'Twig_Template',
        'strict_variables'    => false,
        'autoescape'          => false,
        'cache'               => __DIR__.'/../../cache/twig/',
        'auto_reload'         => null,
        'optimizations'       => -1,
    ));

    $twig = new View($view, $di);
    return $twig;
};

4. Enable Twig as your view engine:

$di['view'] = function() {
    $view = new \Phalcon\Mvc\View();
    $view->setViewsDir(__DIR__ . '/../views/');
    $view->registerEngines(array(
            ".twig" => 'twigService'
    ));
    return $view;
};

That’s it. Create a new file with the extenstion .twig in your view folder, and everything should run as expected.

Many-to-many relationships – Phalcon

If you are working with Phalcon, you will probably need to establish a many-to-many relationship between models. While i was searching in the official documentation, this was not very clear for me at that time. I posted this question on the form, and i got the correct answer.

I will explain you here, step by step. As an example, we will think about the following database structure:

Article table:

CREATE TABLE IF NOT EXISTS `article` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `title` varchar(100) CHARACTER SET latin1 DEFAULT NULL,
  `content` text CHARACTER SET latin1,
  `slug` varchar(160) CHARACTER SET latin1 NOT NULL,
  `created_at` datetime NOT NULL,
  `updated_at` datetime NOT NULL,
  PRIMARY KEY (`id`),
  KEY `title` (`title`,`created_at`),
  KEY `slug` (`slug`)
) ENGINE=InnoDB  DEFAULT CHARSET=utf8 COLLATE=utf8_bin AUTO_INCREMENT=1 ;

Category table:

CREATE TABLE IF NOT EXISTS `category` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `name` varchar(255) CHARACTER SET latin1 NOT NULL,
  `slug` varchar(255) CHARACTER SET latin1 DEFAULT NULL,
  `left_node` int(11) NOT NULL,
  `right_node` int(11) NOT NULL,
  PRIMARY KEY (`id`),
  KEY `idx_name` (`name`),
  KEY `idx_slug` (`slug`)
) ENGINE=InnoDB  DEFAULT CHARSET=utf8 COLLATE=utf8_bin AUTO_INCREMENT=1 ;

articles_categories table:

CREATE TABLE IF NOT EXISTS `articles_categories` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `article_id` int(11) NOT NULL,
  `category_id` int(11) NOT NULL,
  PRIMARY KEY (`id`),
  KEY `article_id` (`article_id`),
  KEY `category_id` (`category_id`)
) ENGINE=InnoDB  DEFAULT CHARSET=latin1 AUTO_INCREMENT=1 ;

ALTER TABLE `articles_categories`
  ADD CONSTRAINT `articles_categories_ibfk_1` FOREIGN KEY (`article_id`) REFERENCES `article` (`id`) ON DELETE CASCADE ON UPDATE CASCADE,
  ADD CONSTRAINT `articles_categories_ibfk_2` FOREIGN KEY (`category_id`) REFERENCES `category` (`id`) ON DELETE CASCADE ON UPDATE CASCADE;

Article model:

hasManyToMany(
      "id",
      "Models\ArticlesCategories",
      "article_id",
      "category_id",
      "Models\Category",
      "id",
      array('alias' => 'categories')
    );
  }
}

Category model:

hasManyToMany(
      "id",
      "Models\ArticlesCategories",
      "category_id",
      "article_id",
      "Models\Article",
      "id",
      array('alias' => 'articles')
    );
  }
}

ArticlesCategories model:

belongsTo('category_id', 'Models\Category', 'id', 
      array('alias' => 'category')
    );
    $this->belongsTo('article_id', 'Models\Article', 'id', 
      array('alias' => 'article')
    );
  }
}

Easy, huh ? See the original post. I hope this was helpful 🙂

Phalcon PHP – i’m lovin it

Since i gave up working with Symfony 1.4, i was searching for a new framework. Because i couldn’t find one that i like, i ended up in developing a small framework by myself. Searching for some solutions related to ORM and ODM, i read some posts related to Phalcon.

Honestly, in a few minutes, i felt in love with this framework. Mainly because of the architecture (very similar with what i developed for myself) and because it is written in C, and it comes as a php extension.

The learning curve should be very fast for any developer that has the basic knowledge about MVC pattern and is familiar with namespaces. Also, the documentation is awesome + that there are a tons of examples on Github.

I am testing it under Ubuntu, Nginx + PHP-FPM – it is incredibly fast. Anyway, there are a lot of improvements that has to be made, but they are moving fast.

All in all, i’m lovin it !