Symfony Doctrine Concurrency

I used Optimistic-Locking here you can find the documentation:

http://docs.doctrine-project.org/projects/doctrine-orm/en/latest/reference/transactions-and-concurrency.html

You can add in your entity the field version. Automatically doctrine will manage concurrency throwing an Exceprion.

use Doctrine\ORM\Mapping as ORM;

... 

 /**
 * @var int
 *
 * @ORM\Column(name="version", type="integer", nullable=true)
 * @ORM\Version
 */
 private $version;
Advertisements
Posted in Symfony | Tagged , , | Leave a comment

Symfony: Gedmo SoftDeleteable Doctrine Entities with Unique Index Columns

This is my solution to avoid constraint violation when you use Soft Delete

Here is an interesting article that explain how unique index are treated by DB
https://mariadb.com/kb/en/mariadb/getting-started-with-indexes/

The field deletedAt as Datetime with NULL value can’t be part of a unique index with NULL value, because you can have duplicate entries with NULL value.

To avoid this problem I added a field called deleted as integer with default value set as 0. When I remove with Soft Delete I set this value equal to the primary key.
So we can add deleted field partecipating in the unique index.

http://intelligentbee.com/blog/2015/01/09/symfony2-gedmo-softdeletable-doctrine-entities-with-unique-index-columns/

http://atlantic18.github.io/DoctrineExtensions/doc/softdeleteable.html

EXAMPLE

app/config/services.yml

services:
    ...
    app.soft_delete_listener:
        class: AppBundle\Events\SoftDeleteListener
        tags:
            - { name: doctrine.event_listener, event: preSoftDelete, priority: 10 }

 

AppBundle\Events\SoftDeleteListener.php

<?php
namespace AppBundle\Events;

use Doctrine\Common\Persistence\Event\LifecycleEventArgs;
use Gedmo\Sortable\Sortable;

class SoftDeleteListener
{
    public function preSoftDelete(LifecycleEventArgs $event)
    {
        $entity = $event->getObject();
        if(method_exists($entity, "getId") && method_exists($entity, "setDeleted")
        {
            $deleted = $entity->getId();
            $entity->setDeleted($deleted);

            $om = $event->getObjectManager();
            $om->persist($entity);
            $om->flush();
        }
    }
}

AppBundle\Entity\User.php

<?php
namespace AppBundle\Entity;

use Doctrine\ORM\Mapping as ORM;

use Gedmo\Mapping\Annotation as Gedmo; // gedmo annotations
use Doctrine\ORM\Mapping\UniqueConstraint;
use Doctrine\Common\Collections\ArrayCollection;

 
/**
 * User
 *
 * @ORM\Table(name="users", uniqueConstraints={@UniqueConstraint(name="item_unique", columns={"username", "deleted"})})
 * 
 * @ORM\Entity(repositoryClass="AppBundle\Repository\UserRepository")
 * @Gedmo\SoftDeleteable(fieldName="deletedAt", timeAware=false)
 * 
 */
class User
{
 /**
 * @var int
 *
 * @ORM\Column(name="id", type="integer")
 * @ORM\Id
 * @ORM\GeneratedValue(strategy="AUTO")
 */
 private $id;

 /**
 * @var string
 *
 * @ORM\Column(name="username", type="string", length=25)
 */
 private $username;

 /**
 * @var \DateTime
 *
 * @ORM\Column(name="deleted_at", type="datetime", nullable=true)
 */
 private $deletedAt;

 /**
 * @var int 
 * 
 * @ORM\Column(name="deleted", type="integer", nullable=false, options={"default":0})
 */
 private $deleted = 0;


 /**
 * Get id
 *
 * @return int
 */
 public function getId()
 {
 return $this->id;
 }


 /**
 * Set username
 *
 * @param string $username
 *
 * @return User
 */
 public function setUsername($username)
 {
 $this->username = $username;

 return $this;
 }

 /**
 * Get username
 *
 * @return string
 */
 public function getUsername()
 {
 return $this->username;
 }

 
 /**
 * Set deletedAt
 *
 * @param \DateTime $deletedAt
 *
 * @return User
 */
 public function setDeletedAt($deletedAt)
 {
 $this->deletedAt = $deletedAt;

 return $this;
 }

 /**
 * Set deleted
 *
 * @param int $deleted
 *
 * @return User
 */
 public function setDeleted($deleted)
 {
 $this->deleted = $deleted;

 return $this;
 }
 
 /**
 * Get deletedAt
 *
 * @return \DateTime
 */
 public function getDeletedAt()
 {
 return $this->deletedAt;
 }

 /**
 * Get deleted
 *
 * @return int
 */
 public function getDeleted()
 {
 return $this->deleted;
 }
 
}
Aside | Posted on by | Tagged , , , | Leave a comment

SQL Access Equivalent MySQL Limit X, Y

In MySQL for paging a query we use

  • SELECT * FROM {table} LIMIT X, Y

In Access there is only

  • SELECT TOP Y * FROM {table}

to select first Y records of a query

We can use this trick:
First we have to know the num_rows of the query

  • NUM_ROWS => “SELECT COUNT(`{$primaryKey}`) FROM {$table} {$where}”

Then we can execute the query we want is equivalent to SELECT * FROM {table} LIMIT X, Y in MySQL

  • SELECT TOP Y * FROM (
    SELECT TOP (NUM_ROWS – X) * FROM {$table} {$where} {$order_inv}
    ) {$order}

Legend:
{$table} is the table name
{$where} is the where condition
{$order} is the order desired
{$order_inv} is the opposite order desired

Posted in Access, PHP, SQL | Tagged , , , , | Leave a comment

HTML JQuery – transform Inputbox into dropdown list (combobox)

Transform input textbox in combobox using JQuery and hide click out

Demo

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>JQuery - Dropbox</title>
<script type="text/javascript" src="/js/jquery-1.4.2.min.js"></script>
<script type="text/javascript" src="/js/jquery-ui-1.8.2.custom.min.js"></script>
<link rel="stylesheet" type="text/css" href="/css/ui-lightness/jquery-ui-1.8.2.custom.css"/>

<style type="text/css">
ul {
	margin: 0;
	padding: 0;
}
li {
	list-style: none;
}
#dropdown { position:absolute; width:200px; display:none; }
#dropdown li:hover { background:#ccc; cursor:pointer; }
#dropdown li {
    border: 1px solid #DEDEDE;
	
}
</style>
<script>

$(function() {
	$('#btn').click(function(e) {
		
		var pos = $('#txt').offset();
		pos.top += $('#txt').height();
	
		if($('#dropdown').is(':visible')) {
			   //str = 'visibile';
			   $('#dropdown')
			   	.removeClass('active')
				.fadeOut(100);
		} else {
			   //str = 'NOT visible';
			   $('#dropdown')
			     .addClass('active')
			   	.fadeIn(100);
		}
		
		e.stopPropagation();
		
		return false;
	});

	$('#dropdown li').click(function() {
		$('#txt').val($(this).text());
		$(this).parent().fadeOut(100);
	});

    $(document).click(function (e) {
        $('#dropdown').fadeOut(100);
    });
});
</script>    
</head>

<body>

<input type="text" id="txt" />
<button id="btn">Select </button>

<ul id="dropdown">
    <li>Value 1</li>
    <li>Value 2</li>
    <li>Value 3</li>
    <li>Value 4</li>
    <li>Value 5</li>
</ul>

</body>
</html>
Posted in JQuery | Tagged , , | Leave a comment

PHP JQuery – Trick Ajax external site (cURL)

Here is a way to call through Ajax an external link
we use curl in a PHP function to read external url and print result in a Dialog Box

example.html

<!doctype html>
 <html lang="en">
 <head>
 <meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>
 <title>PHP JQuery - Trick Ajax external site</title>

<link rel="stylesheet" href="http://ajax.googleapis.com/ajax/libs/jqueryui/1.10.3/themes/ui-lightness/jquery-ui.css" type="text/css" media="all" />

 <script src="//ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
 <script src="//ajax.googleapis.com/ajax/libs/jqueryui/1.10.3/jquery-ui.min.js"></script>
  
<script type="text/javascript">
function getWrapper() {
  var request = $.ajax({
    url: "wrapper.php",
    data: {
     
    },
    dataType:   "html", 
    beforeSend: function() {
   
    },              
    success: function(data){
 
      var tag = $("<div></div>"); //This tag will the hold the dialog content.
         
             
      tag.html(data).dialog({
                            modal: true, 
                            title: 'Ajax', 
                            width: 'auto',
                            show: 'blind',
                            hide: 'blind'
                        }).dialog('open');                  
    },
    complete:   function() {
    
    },
    error: function() {
     alert('Error');
    },          
  });
}
  
 
 $(document).ready(function() {
   $('#cmd').click( function() {
     getWrapper();     
   });
 });
</script>
</head>
  
<body>
<button id="cmd" name="cmd" >Open</button>
</body>

wrapper.php

$url = "http://www.google.com";
echo readHTML($url);

function readHTML($url) { 
    if(!function_exists("curl_init")) return "cURL extension is not installed";
    if (trim($url) == "") die("@ERROR@");
    $curl = curl_init($url);
    curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);                         
    curl_setopt($curl, CURLOPT_USERPWD, 'username:password');
    curl_setopt($curl, CURLOPT_HTTPAUTH, CURLAUTH_ANY);                    
    curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false);                          
    curl_setopt($curl, CURLOPT_FOLLOWLOCATION, true);                           
    $response = curl_exec($curl);                                          
    $resultStatus = curl_getinfo($curl);                                   
    if($resultStatus['http_code'] == 200) {
        // All Ok
    } else {
        echo 'Call Failed '.print_r($resultStatus);                         
    }
    $curl = null;
    return utf8_encode($response);      
} //* readHTML */
Posted in JQuery, PHP | Tagged | 2 Comments

PHP transform array to an HTML table

PHP transform array to an HTML table

//---Show an array content (1st level) in a HTML table format
// $option = array(
//		'order' => '{field}',	- list fields on which order and show
//		'options' => array(
//			'field_color_row' => 'red' / '#FFFFFF'	// row color
//			'cellpadding' => '5' / '#FFFFFF'		// cellpadding table
//			'cellspacing' => '0' / '#FFFFFF'		// ininfluente con bordercollapse
//			'classtable' => 'nameClassTable' 		// class table
//		),
//		'{field}' => array(
//			'header' => '{Name Field 1}'				//Header column
//			'type' => 'date' / 'integer', 'income'		//type data
//			'align' =>	'left' / 'center' / 'right'		//align
//			'class' => 'nameClass'					//column class <td>
//			'unit' => 'kg'								//unit measure
//		)
// $id - id table to assign
function showTable($array, $options = array(), $id = ''){
	if(is_array($array))  {
		//---reorder $array defined in $options['order']
		if(isset($options['order'])) {
			
			$array1 = array();
			$array_order = $options['order'];
			foreach ($array as $key => $item){
				$array2 = array();
				foreach ($array_order as $field){
					$array2[$field] = $item[$field];
				}
				$array1[$key] = $array2;
			}
			
			$array = $array1;
		}
		
		//---options field on which set color (if not defined alternate color)
		$field_color_row = "";
		if(isset($options['options']['field_color_row'])) {
			$field_color_row = $options['options']['field_color_row'];
		}

		//---options cellpadding
		$cellpadding = "0";
		if(isset($options['options']['cellpadding'])) {
			$cellpadding = $options['options']['cellpadding'];
		}
		//---options cellspacing
		$cellspacing = "0";
		if(isset($options['options']['cellspacing'])) {
			$cellspacing = $options['options']['cellspacing'];
		}
		//---options cellpadding
		$classtable = "";
		if(isset($options['options']['classtable'])) {
			$classtable = $options['options']['classtable'];
		}
								
		?>
        <table <?= $id ? 'id="'.$id.'"' : ''; ?> <?= $classtable ? 'class="'.$classtable.'"' : '';?>" border="1" cellpadding="<?= $cellpadding;?>" cellspacing="<?= $cellspacing;?>" style="border-collapse:collapse">
        
        <?
		$n = 0;
		$prev = "";
		$flag_header = true;
		foreach ($array as $key => $item){

			if($field_color_row) {
				if($item[$field_color_row] != $prev) {
					$prev =	$item[$field_color_row];
					$n++;
				}	
			} else {
				$n++;
			}
			
			$class = "odd";
			if ($n % 2 == 0){
				$class = "even";
			}
				
			
			if($flag_header) {
				?>
                <thead>
                <tr class="head">
                <?
				foreach(array_keys($item) as $campo) { 
					if(isset($options[$campo]['header']) && $options[$campo]['header']) {
						$campo = $options[$campo]['header'];
					}
				
				?>
					<th><?= $campo ?></th>
                <?
				}
				?>
                </tr>
                </thead>
                <tbody>
                <?
				$flag_header = false;
			}//End if($flag_header) {
			?>
            	<tr class="<?= $class; ?>">
            <?
			if(is_array($item)) {
			foreach($item as $key => $el) { 
				$align = 'left';
				if(isset($options[$key]['type']) && $options[$key]['type']) {
					//---tipo formato
					switch($options[$key]['type']) {
//						case 'checkbox':
//							$align = 'center';
//							$el = '<input name="chk" type="checkbox" ' . ($el ? 'checked="checked"' : '') . ' value="' . $el . '" />';
//							break;
						case 'date':
							$el = RigiraData(EpuraData($el));
							break;
						case 'integer':
							$align = 'right';
							$el = frwt_printNumber($el, $dec = 0);
							break;
                                                case 'currency':
						case 'income':
							$align = 'right';
							$el = frwt_printNumber($el, $dec = 2);
							break;	
					}

					//echo "el=".$el."<br />";
					//die("TEST");
				}

				if(isset($options[$key]['unit']) && $options[$key]['unit']) {
					//---unit measure
					$unit = $options[$key]['unit'];
					$el .= " " . $unit;
				}

				if(isset($options[$key]['align']) && $options[$key]['align']) {
					//---align
					$align = $options[$key]['align'];
				}
				
				//---class
				$td_class = "";
				if(isset($options[$key]['class']) && $options[$key]['class']) {
					$td_class = $options[$key]['class'];
				}
				?>
					<td <?= $td_class ? 'class="'.$td_class.'"' : ''; ?> valign="top" align="<?= $align;?>"><?= $el ?></td>
                <?
			}//End foreach($item as $el) {
			}
			?>
            	</tr>
			<?
			
			
		}//End foreach ($array as $key => $item){
		?>
        </tbody>
        </table>
        <?
	}
}

Example with MySQL

$SQL = "SELECT name, surname, city FROM users");
$res = mysql_query($SQL);
while($item = mysql_fetch_assoc($res)) {
  $array[] = $item;
);

showTable($array);

Results

name surname city
Kobe Bryant Los Angeles
Mike Smith New York
Mark Anthony Chicago
Dave Sullivan San Francisco
Posted in PHP | Tagged , , | Leave a comment

JQuery click + shift button for selecting group of checkboxes as desktop application

Click start checkox and then click + shif button on end checkbox

<!doctype html>
 <html lang="en">
 <head>
 <meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>
 <title>JQuery checkbox click + shift</title>
<style>
 table tr td input.selected {
 outline-color:#6CF;
 outline-style:solid;
 outline-width:thin
}
 </style>
 <script type="text/javascript" src="jquery-1.7.1.min.js" charset="utf-8"></script>
 <script type="text/javascript" src="jquery-ui-1.8.17.custom.min.js" charset="utf-8"></script>

<script type="text/javascript">
 $(document).ready(function() {
 TABLE.selectable('#contacts');
 });

var TABLE = {};

TABLE.selectable = function(table) {
    var $tables = $(table);

    $tables.each(function () {
        var _table = $(this);
/*
//        _table
//            .find('thead tr th:nth-child(1)')
//            .before($('<th><input id="checker" type="checkbox" value="Select" /></th>'));
//        _table
//            .find('tbody tr td:nth-child(1)')
//            .before($('<td><input type="checkbox" value="Select" /></td>'));
*/
        var chkSelector = 'tr td:nth-child(1) :checkbox';
        //--- this one if you put in class for each checkbox class="checbox"
        //var chkSelector = '.checkbox';

        $('#checker').click(function() {
            _table.find(chkSelector)
                .prop('checked', $(this).prop('checked'));        
        });

        _table.find(chkSelector).click(function(e) {
            var $table = $(this).parents('table');
            var lastRow = $table.data('lastRow');
            var lastIndex = $table.data('lastIndex');

            var thisRow = $(this).parents('tr').index();

            //---THIS INDEX
            var str = $(this).attr('index');
            //var pos = str.lastIndexOf('_');
            var thisIndex = parseInt(str);
            //str = str.substring(0,pos+1) + str.substring(pos+1)

            var checked = $(this).prop('checked');

            _table.find(chkSelector).removeClass('selected');
            $(this).addClass('selected');

            //if(lastRow !== undefined && e.shiftKey) {
            if(lastIndex !== null && e.shiftKey) {                
                var numChecked = 0;
                //var start = lastRow < thisRow ? lastRow : thisRow;
                //var end = lastRow > thisRow ? lastRow : thisRow;

                var start = lastIndex < thisIndex ? lastIndex : thisIndex;
                var end = lastIndex > thisIndex ? lastIndex : thisIndex;

                $table
                    .find(chkSelector)
                    .slice(start, end + 1)
                    .prop('checked', checked);

//                var $list =    $table
//                    .find(chkSelector);
//                alert($list.length);
//                alert($list.slice(start, end + 1).prop('checked', checked).length);
            }
            $table.data('lastRow', thisRow);
            $table.data('lastIndex', thisIndex);

        });
    });
}
</script>
</head>

<body>
  <table id="contacts" style="border-collapse:collapse" border="1" cellpadding="5" align="center">
    <thead>
      <tr>
        <th><input id="checker" type="checkbox" value="1" /></th>
        <th>Contact</th>
      </tr>
    </thead>
    <tbody>
      <tr>
        <td><input type="checkbox" value="1" index="0" /></td>
        <td>Mike Brown</td>
      </tr>
      <tr>
        <td><input type="checkbox" value="1" index="1" /></td>
        <td>Chris Mullin</td>
      </tr>
      <tr>
        <td><input type="checkbox" value="1" index="2" /></td>
        <td>Scottie Pippen</td>
      </tr>
      <tr>
        <td><input type="checkbox" value="1" index="3" /></td>
        <td>Micheal Jordan</td>
      </tr>
      <tr>
        <td><input type="checkbox" value="1" index="4" /></td>
        <td>Grant Hill</td>
      </tr>
      <tr>
        <td><input type="checkbox" value="1" index="5" /></td>
        <td>Alonso Mourning</td>
      </tr>  
      <tr>
        <td><input type="checkbox" value="1" index="6" /></td>
        <td>David Rivers</td>
      </tr>  
      <tr>
        <td><input type="checkbox" value="1" index="7" /></td>
        <td>Carlton Myers</td>
      </tr>                                          
    </tbody>
  </table>
</body>
</html>
Posted in checkbox, JQuery | Tagged , , , | 2 Comments