If you are a developer do not

If you are a developer do not:

  • use inline style
  • duplicate your code
  • comment out old code
  • stretch images
  • use alpha or beta plugins / frameworks / cms
  • do and undo things in the same function
  • optimize code at first stage
  • write deeply nested code
  • start implementing something until you have  specifications
  • add meaningless variable names
Thank You!

 

Allow user to choose role at registration in Symfony2 FOSUserBundle

FOSUserBundle is a great bundle for Symfony2 that implements Security, Authenticity and Authorization for Users. Though is very easy to install and override, it needs a good understanding of the Symfony2′s philosophy, in order to do that in a good manner.

I needed to override the registration process offered by the bundle, in order that the user might choose the role, this feature doesn’t come by default with the bundle.

The steps for doing this task are the following (of course, most of them can be found at FOSUserBundle documentation):

MainUserBundle is the bundle that contains the User entity that extends the User in FOSUserBundle.

1. In MainUserBundle in services.yml I had to add

services:
  main_user.registration.form.type:
    class: Main\UserBundle\Form\Type\RegistrationFormType
    arguments: [%fos_user.model.user.class%,
                      %security.role_hierarchy.roles%]
    tags:
      - { name: form.type, alias: main_user_registration }

Notice %security.role_hierarchy.roles%, this was added in order that the form should receive as parameter an array with all the roles specified in app/config/security.yml. This is necessary because the form is instantiated through the above service:

$form = $this->container->get('fos_user.registration.form');

2. Created the RegistrationFormType.php in my bundle extending the form FOSUserBundle in Main/UserBundle/Form/Type/RegistrationFormType.php.

In this form I had to override also the constructor to tell him to receive the parameter which contained the roles.

 public function __construct($class, $roles_hierarchy = null)
    {
        $this->roles_hierarchy = $roles_hierarchy;
    }

And so I can add a form choice field for role,  with the available choices being the array from the constructor.

3. Finally I had to modify app/config/config.yml
fos_user:
    ...
    registration:
        form:
            type:
              main_user_registration //this is the same alias
                    specified in services

That’s all!

 

Symfony2 Sonata Admin Bundle Custom Action

Sonata Admin Bundle implements for Symfony2 the correspondent to AdminGenerator plugin from Symfony version 1.4. It’s easy to install, and not so hard to configure, but it can get a little bit complicated especially if you don’t understand completely the philosophy of Symfony2 (this is my case).

Anyway, with the help of the online documentation available I manage the configure the Sonata AdminBundle and I will list here the steps required to create own list actions for entities without modifying the bundle.

There are some actions that exist by default as is edit, view or delete, but in my case, I had to work with books, I needed to implement publish action for each book, in the following way:

1. In MyBundle/Admin/BookAdmin  (Book is the name of the entity) overide the method:

public function configureListFields(ListMapper $listMapper) {
 $listMapper
 //add fields
 // add custom action links  
 ->add('_action', 'actions', array( 'actions' => array(  
 //....
 'unpublish' => array('template' =>
 'MyBundle:Admin:action_unpublish.html.twig'),)));
} 

This action has a number of optional values that can be declared in an array, and among them is the template option through which you can specify the template that displays the link to this action.

The template I used was located in MyBundle (the bundle that contained the entity) in Resources/Views/Admin

3.  In BookAdmin override the method configureRoutes to add the route for that action

Don’t forget the namespace!


use Sonata\AdminBundle\Route\RouteCollection;

class BookAdmin extends Admin {

...

protected function configureRoutes(RouteCollection $collection) {
 $collection->add('unpublish',
 $this->getRouterIdParameter().'/unpublish'); }

}

4. Create the action in MyBundle/Controller/BookAdminController with the name publishAction($id)

In this action you may put the desired logic.

Change the value of a hidden input field

       I wanted to change the value of a hidden input field when a radio button is selected:

   <input type="radio" name="item1" class="items" value="5" />5
   <br/>
   <input type="radio" name="item2" class="items" value="25" />25
   <br/>
   <input type="hidden" name="hidd" id="hidd_item" value="" /> 

For example when a user clicks on one of the radio buttons, the value of hidden input field changes to that value.

My solution – the jQuery function bellow (for this to work you need jQuery installed and setup) :

  <script>
     $('.items').click (function () {
         var value = $(this).val();
         $('#hidd_item') .val(value);
       });
  </script>

Hope this was useful. Happy coding!

 

Symfony2 Generate Entities Starting from a Database

As I figured it out, until now, Symfony2 hasn’t got a common schema.yml for all entities (an entity is a class/object that maps the correspondent table) as was in Symfony 1.4, but the database configurations are made separate for every entity. In these conditions creating a database starting from the existing entities is a much more laborious task than it was in Symfony 1.4, but not impossible.

There is, although, another solution to this problem, building the entities starting from an existing database. There is a good tutorial in Symfony2 cookbook, but I will also list here the commands needed to complete this task. All of these commands assume that I configured the parameter.ini correctly, so Symfony knows which is the database to use, and also that the bundle Main/MyBundle is initialized, in order to store the entities that will be created.

1. First Symfony needs to generate the metadata corresponding to the tables through the following command. This will create YAML files but it can also create XML files.

     php app/console doctrine:mapping:convert yml ./src/Main/MyBundle /Resources/config/doctrine/metadata/orm --from-database --force

2. Now Symfony can import the configurations from the metadata files

     php app/console doctrine:mapping:import MainMyBundle yml

3. The entities can be generated based on the configuration files

     php app/console doctrine:generate:entities MainMyBundle

That’s all!

But one needs to pay attention to the way he builds his database from the beginning.  For example the relations too must be specified when building the database otherwise Doctrine will not be able to detect them. In phpMyAdmin this is done in the following way:

  • go to the structure of the table that will contain the foreign key
  • create an index on the field that you want it to be a foreign key
  • go back to the structure of the table and click Relation View
  • on the field that we want to make a foreign key specify to which other key it is related

For example if you want to have two tables book and author, than the primary key will be in author table, since it is unique, but one author can write one or many books, and the foreign key will be the author_id field in book table.

Preload images – with CSS, NO JavaScript

          Web designers preload images to speed up page display. Even though JavaScript is the most common way to preload images, it is not the only option.

          How to preload images without JavaScript? This article proposes a new method to preload images without the use of JavaScript, so consider using the CSS DISPLAY property instead. It may be more reliable and it requires less complex code. With this technique your viewers will have the necessary images in their browser’s cache before the script starts to run.

         The solution: you may add background images to elements that are empty and use the css property “display: none;”. For example, to preload three images: image1.png, image2.png, and image3.png, locate three appropriate elements in your markup and place something like this into your CSS file:

#preload_image1 {

    background: url(path/image1.png) no-repeat;

    display: none;

}

#preload_image2 {

    background: url(path/image2.png) no-repeat;

    display: none;

}

#preload_image3 {

    background: url(path/image3.png) no-repeat;

    display: none;

}

Symfony 1.4 Forms: Check if two fields have the same value

In Symfony 1.4 you may check if two fields have the same value, especially useful when you have to confirm password, email address or other fields.

Add the extra confirmation fields to your SomethingForm.class.php by adding the following lines:

$this->setValidator(‘confirm_password’ , new sfValidatorString(array(‘required’ => true)));

Add as post validator checking two fields values.

$this->validatorSchema->setPostValidator(
new sfValidatorAnd(array(
new sfValidatorSchemaCompare(
‘password’,  sfValidatorSchemaCompare::EQUAL, ‘confirm_password’,
array(),
array(‘invalid’ => “Please enter the same password address.”))
))
);

That’s All. When you enter different values in password and confirm_password fields you’ll see the error message.

 

 

 

 

Facebook Page – Best practice

Lot of people think that creating a facebook page is very easy, 1-2 minutes creating an account and waiting for thousands of likes. They don’t know the truth. You have to care about your page, interact with your fans.

Here are some tips, best practice for your facebook page:

  • update daily, interact with your fans
  • write more about educational / entertaining information and less about your organization
  • ask questions, solicit your fans input
  • integrate application, facebook offers thousands of application to use on your page
  • make your fans feel special.  Encourage them to speak.
  • timing. Don’t share all your news at 04:00am ,  share one in the morning, other at noon, and if you have something to say latter you can share it evening.
These are some of the best practice for your facebook page.

 

 

Symfony 1.4 Admin Generator Override Templates and Actions

Admin Generator  for Symfony 1.4 is a powerful tool that creates a fully operational backend application, for administering the site.

The idea behind it, is to create fully operational modules based on module classes, by specifying the model class name in the line command that creates the module:

php symfony doctrine:generate-admin backend Profile

Another important aspect is the generator.yml file which  contains all the configuration necessary for the Admin Generator. Also they also provide a default styling made available by typing the following comand on the console:

$ php symfony plugin:publish-assets 

This article is not a tutorial about how to implement Admin Generator since Symfony’s tutorial is a very good one, but my aim is to underline only some aspects that aren’t so well documented in the official documentation.

A problem I faced was the need to make conditional object actions, that depend on the state off the object.

The solution was to override the _list_td_actions.php file that is situated in the cache. All the files for the backend are generated every time and are stored in cache. In the new template, I had the object upon which I made the action, and it contained all the data from its table in the database, so it was easy to put a condition concerning the state of the object.The same thing can be done with batch actions.

There were several solutions provided on Symfony’s forums but none of them worked, so the solution I implemented was to copy the needed templates in the backend app, keeping their path the same.

<?php if($profile['is_active'] == 1): ?>
  <li>
   <?php echo link_to(__('Deactivate', array(), 'messages'), 
 'profile/ListDeactivate?id='.$profile->getId(), array()); ?>
  </li>
<?php endif; ?>

One important thing here is that when changes are being made to the generator.yml, concerning the template, the template in the backend app previously copied is not modified so it has to be copied again.

Working with Aggregator module in Drupal 7

Aggregator is a module which is included among the core modules of Drupal 7 and it represents a feed reader, that fetches syndicated content (that is feeds) from other websites.

This module allows Drupal developers to add as many feeds they want, and even group them by category. Also, once enabled, there must be made some general configuration, through which one can specify the number of items to appear in the feeds page.

When adding a new feed, one must specify the feed URL from which the content will be brought, and a page will be created with all those feeds. It also must be set the update interval in which cron will update the feeds. This module also permits the creation of simple blocks with the feeds titles, and links to the original website from which the content was brought.

If you have the Views module installed, than, upon enabling Aggregator module, a new type of view appears, Aggregator item. This type of view allows you to build custom pages and blocks with the feeds content specified in the feed URL previously created.

This is a powerful tool for building a rss reader inside your Drupal website and it is also very easy to use.