Tuesday 3 May 2011

CakePHP: Dynamicaly disabling links

Sometimes we get buried so deeply into ... nuclear science that we forget that after all CakePHP is just PHP, the resulting pages are just HTML and you don't need JQuery to disable a link. Setting it's onlick event to return false, usually does it.

The problem was simple: Given a list of records, (arrivals) selectively enable an action link for each record, (create a purchase order in our case). based on a record attribute (that is whether the purchase order has already been created).

Now, that is now so hard. Well, if you already have something like :

<?php echo $this->Html->link(
                    $this->Html->image('actions/upload.png'),
                    array(
                          'action' => 'createPurchasOorder',
                          $arrival['Arrival']['id']
                    ),
                    array(
                      'escape' => false,
                      'title' => 'Create purchase order for the arrival.'
                    )
                ); ?> 

inside a PHP foreach loop, then it's not that difficult to transform it into :

<?php 
         $canCreatePO = empty($arrival['Arrival']['purchase_order_code']);
         echo $this->Html->link(
                    $this->Html->image('actions/upload.png'),
                    array(
                          'action' => 'createPurchasOorder',
                          $arrival['Arrival']['id']
                    ),
                    array(
                      'escape' => false,
                      'onclick' => $canCreatePO 
                              ? 'return true;'
                              : 'return false',
                      'title' => $canCreatePO 
                              ? 'Create purchase order for the arrival.'
                              : 'Purchase order has already been created.'
                    )
                ); ?> 

So, why the hell did it take me an entire morning to figure this out....

No comments :