Code
Just a few notes for me
Import new project:
$ svn import -m "Initial" project_folder https://domain.com/svn/project_folder
Checkout project with .svn files
$ svn checkout https://domain.com/svn/project_folder destination_folder
Export project without .svn files
$ svn export https://domain.com/svn/project_folder destination_folder
Delete folder
$ svn delete -m "Deleting project dir" https://domain.com/svn/project_folder/destination_folder
Find .svn files and delete them
$ find path_to_folder -name .svn -exec rm -R '{}' \;
- Postal code
- DNI/NIF validation
- Hour:minute:second
- Replace strings in SQL query
- Search breakline
Postal code
This will check european postal code (eg: 28008) and US postal code (eg: 12005-1234)
if (preg_match('/^\d{5}(-\d{4})?$/', $postalCode)) { // valid postal code } else { // invalid postal code }
DNI/NIF validation
PHP
/** * Checks valid dni/nif and returns true|false * @param string $nif * @return boolean */ function validateNif($nif) { $nif_codes = 'TRWAGMYFPDXBNJZSQVHLCKE'; $sum = (string) $this->getCifSum($nif); $n = 10 - substr($sum, -1); if (preg_match('/^[0-9]{8}[A-Z]{1}$/', $nif)) { // DNIs $num = substr($nif, 0, 8); return ($nif[8] == $nif_codes[$num % 23]); } elseif (preg_match('/^[XYZ][0-9]{7}[A-Z]{1}$/', $nif)) { // standar NIEs $tmp = substr($nif, 1, 7); $tmp = strtr(substr($nif, 0, 1), 'XYZ', '012') . $tmp; return ($nif[8] == $nif_codes[$tmp % 23]); } elseif (preg_match('/^[KLM]{1}/', $nif)) { // special NIFs return ($nif[8] == chr($n + 64)); } elseif (preg_match('/^[T]{1}[A-Z0-9]{8}$/', $nif)) { // strange NIE return true; } return false; } /** * * @param string $cif * @return string */ function getCifSum($cif) { $sum = $cif[2] + $cif[4] + $cif[6]; for ($i = 1; $i < 8; $i += 2) { $tmp = (string) (2 * $cif[$i]); $tmp = $tmp[0] + ((strlen($tmp) == 2) ? $tmp[1] : 0); $sum += $tmp; } return $sum; }
Javascript (simple)
/** * Validate DNI * @param {String} dni * @returns {Boolean} */ function validateDNI(dni) { var number; var let; var nif_codes = 'TRWAGMYFPDXBNJZSQVHLCKET'; var regular_expresion_dni = /^\d{8}[a-zA-Z]$/; if (regular_expresion_dni.test(dni) === true) { number = dni.substr(0,dni.length-1); let = dni.substr(dni.length-1,1); number = number % 23; nif_codes = nif_codes.substring(number, (number + 1)); if (nif_codes !== let) { return false; } else { return true; } } else { return false; } }
Javascript
function isValidEmail(email) { var regex = /^(([^<>()[\]\\.,;:\s@\"]+(\.[^<>()[\]\\.,;:\s@\"]+)*)|(\".+\"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/; return regex.test(email); }
PHP
function isValidEmail($email) { return filter_var($email, FILTER_VALIDATE_EMAIL) && preg_match('/@.+\./', $email); }
Hour:minute:second
/** * Checks valid hour:minute or hour:minute:second * @param string $hour * @param string $format [optional] H:i | H:i:s * @return boolean */ function isValidHour($hour, $format = 'H:i') { $isValidHour = false; switch ($format) { case 'H:i': if (preg_match("/^([01]?[0-9]|2[0-3]):[0-5][0-9]$/", $hour)) { $isValidHour = true; } break; case 'H:i:s': if (preg_match("/^([01]?[0-9]|2[0-3]):[0-5][0-9]:[0-5][0-9]$/", $hour)) { $isValidHour = true; } break; } return $isValidHour; }
Replace strings in SQL query
// replace SELECT params to count(*) $sql = preg_replace('/SELECT (.*) FROM/i', 'SELECT COUNT(*) AS total FROM', $sql); // unset ORDER $sql = preg_replace('/ORDER BY (.*)/i', '', $sql);
Search breakline
$replace = preg_replace('/<\?[\r\n]/', '<?php', $string);
Find text inside all files in a folder recursively with grep command
grep -iRHn "searchText" path_to_folder
Concatenate another grep command to exclude some files, e.g: svn files
grep -iRHn "searchText" path_to_folder | grep -v ".svn" > save_ocurrences_in_a_file.txt
Find any files in a folder and sort them by last updated
Find files of a certain user with users write permissions and without group write permissions
find path_to_folder -user user_name -type f -perm /u+w ! -perm /g+w
Concatenate another command to add write permissions
Search recursively symbolic links
find path_to_folder -type l -exec ls -lad {} \;
Find zip files older than 5 days and delete them
find -name '*.zip' -type f -mtime +5 -exec rm -f {} \;
Find .svn files and delete them
find path_to_folder -name .svn -exec rm -R '{}' \;
Search recursively a folder and set permissions for web apps (644 for files, 755 for folders)
Find files by size, show the top 10
du -hsx * | sort -rh | head -10
- du command : Estimate file space usage.
- sort command : Sort lines of text files or given input data.
- head command : Output the first part of files i.e. to display first 10 largest file.
Script to save as "multitail.sh' or whatever you like. Save it in "/home/username/scripts" or any other folder
Edit your .bashrc or your .profile (both inside your user folder, e.g. /home/username/.profile)
Add alias
alias tail='/home/username/scripts/multitail.sh'
Just type in the shell "tail filename1 filename2 filename3"
Source: http://www.thegeekstuff.com/2009/09/multitail-to-view-tail-f-output-of-m...
Display columns name from a table sort by Field name from shell
- Step 1: create bash script
- Step 2: use example
Step 1: create bash script
File name: desc.sh
#!/bin/bash db_user="database_user" db_pass="database_pass" db_name="database_name" db_host="database_host" # table name from user input db_table=$1 mysql -u${db_user} -p${db_pass} ${db_name} -h ${db_host} -e "SELECT c.COLUMN_NAME as 'Field', c.COLUMN_TYPE as 'Type', c.IS_NULLABLE as 'Null', c.COLUMN_KEY as 'Key', c.COLUMN_DEFAULT as 'Default', c.EXTRA AS 'Extra', c.COLLATION_NAME as 'Collation', c.COLUMN_COMMENT as 'Comment', t.ENGINE as 'Engine', t.TABLE_ROWS as 'Rows' FROM INFORMATION_SCHEMA.COLUMNS as c, INFORMATION_SCHEMA.TABLES as t WHERE c.TABLE_NAME = '${db_table}' AND c.TABLE_SCHEMA = '${db_name}' AND t.TABLE_NAME= '${db_table}' AND t.TABLE_SCHEMA = '${db_name}' ORDER BY Field ASC"
Step 2: use example
- Give execution permission
chmod +x desc.sh
- Try it
./desc.sh table_name
Ejemplo para mostrar una variable normal:
<span> Fecha actual: {{ fechaActual }} </span>
- {{ variable }} equivale a echo $variable, aunque no suelta E_NOTICE si no está definida.
Ejemplo para mostrar una array:
<span> Valor del array: {{ arrayEjemplo.indice }} </span> <span> Otra forma para lo mismo: {{ arrayEjemplo['indice'] }} </span>
Ejemplo para recorrer una array/objeto en un bucle:
{% for indice, Modelo in Modelos %} <span>Valor de variable: {{ Modelo.variable }}</span> <span>Valor del indice del bucle: {{ indice }}</span> {% endfor %}
- Más ejemplos: http://twig.sensiolabs.org/doc/tags/for.html
Ejemplo para crear una variable en la plantilla Twig:
{% set variableTwig = 'valor' %} <span>Valor de la variable: {{ variableTwig }}</span>
Ejemplo para mostrar un objeto:
<span> Propiedad "nombre" del objeto: {{ modelo.nombre }} </span>
Ejemplo para mostrar una variable que tenga HTML dentro:
<span> Variable con html: {{ variableConHTML | raw }} </span>
Ejemplo para hacer dump de cualquier cosa:
<span> Dumpeando modelo: {{ dump(modelo) }} </span>
Ejemplo para ver si una variable está definida y vale algo:
<span>{% if fechaActual is not null %} {{ fechaActual }} {% endif %}</span>
Operadores condicionales and|or:
{% if (variable1 is not null and variable2 > 0) or variable == 3 %} {{ variable3 }} {% endif %}
Ejemplo para incluir una vista dentro de otra:
{% if modelo.msgError is not null %} {% include 'comun/errorFormulario.twig' %} {% endif %}
Ejemplo para concatenar un texto con una variable:
<span>{{ modelo.variable }} ~ '_' ~ {{ modelo.variable2 }}</span>
Se utiliza el carácter ~ para concatenar
Ejemplo para crear un filtro personalizado
PHP
// añadir filtro "t" para traducir cadenas $function = new Twig_SimpleFilter('t', function ($texto) { return traducirTexto($texto); }); $twig->addFilter($function);
HTML
<h1>{{ 'Título principal traducido' | t }}</h1>
Ejemplo para crear un filtro personalizado añadiendo un parámetro extra
PHP
// añadir filtro "t" para traducir cadenas $function = new Twig_SimpleFilter('t', function ($texto, $parametroExtra = 'es') { if ($parametroExtra == 'es') { return traducirTexto($texto); } else { return $texto; } }); $twig->addFilter($function);
HTML
<h1>{{ 'Título principal traducido' | t("parametroExtraCualquiera") }}</h1>
- The objective is to save form data with file inputs and AJAX.
- Step 1: process files before the rest of data, save them to disk and database.
- Step 2: process the rest of field inputs, validate and the save them all.
HTML
<div id="wrapper"> <form id="example-form" method="post" action=""> <div class="form-group"> <label for="Model[name]">Text input</label> <input type="text" class="form-control" name="Model[name]"> </div> <div class="form-group"> <label for="Model[file]">File input</label> <input type="file" class="form-control" name="Model[file]"> </div> <div class="form-group"> <label for="Model[file2]">File input 2</label> <input type="file" class="form-control" name="Model[file2]"> </div> <input type="submit" class="btn btn-primary" value="Send"> <div id="ajax-form-results"></div> </form> </div>
Javascript
// Variable to store your files var files; // on submit, preprocess files $('#wrapper').on('submit', 'form', uploadFiles); /** * Catch the form submit and upload the files * @param {object} event * @returns {Boolean} */ function uploadFiles(event) { // create a formdata object and add the files #} var filesData = new FormData(); // find files var files = []; $(this).find('input[type="file"]').each(function() { if ($(this).val() !== "") { files.push($(this)[0].files[0]); } }); // if form has files... if (files.length > 0) { $.each(files, function (key, value) { filesData.append(key, value); }); $.ajax({ url: 'ajaxFileUpload.php', type: 'POST', data: filesData, cache: false, dataType: 'json', processData: false, // Don't process the files contentType: false, // Set content type to false as jQuery will tell the server its a query string request success: function (filesData) { if (data.success === true) { // success so call function to process the form submitForm(event, filesData); } else { // handle errors here $('#ajax-form-results').html(filesData.error); } }, error: function (filesData) { // handle errors here console.log('Errors ajaxFileUpload: ' + filesData.error); } }); } else { // process the form without files submitForm(event, filesData); } return false; } // end uploadFiles() /** * Proccess the form submit * @param {object} event * @param {object} filesData * @returns {void} */ function submitForm(event, filesData { // create a jQuery object from the form var form = $(event.target); // serialize the form data var formData = form.serialize(); // if the form has files, add to formData if (filesData.length > 0) { $.each(filesData.files, function (key, value) { formData = formData + '&filenames[]=' + value; }); } $.ajax({ url: 'ajaxSubmitForm.php', type: 'POST', data: formData, cache: false, dataType: 'json', success: function (data) { if (data.success === true) { // do whatever, send a OK message for example $('#ajax-form-results').html(data.message); // we can refresh some page content here... } else { // Handle errors here $('#ajax-form-results').html(data.error); } // in case we made a submit form by Bootstrap modal, hide it by force $('body').removeClass('modal-open'); $('.modal').modal('hide'); $('.modal-backdrop').remove(); }, error: function (data) { // Handle errors here console.log('Errors ajaxSubmitForm: ' + data.error); } }); } // end submitForm
ajaxFileUpload.php
<?php $data = []; // if any files, start... if (isset($_FILES[0])) { $success = true; $files = []; // upload dir example $uploadDir = 'uploads/files/'; if (!is_dir($uploadDir)) { mkdir($uploadDir); } foreach ($_FILES as $file) { $fileName = time() . '_' . $file['name']; if (move_uploaded_file($file['tmp_name'], $uploadDir . basename($fileName))) { $fileModel = new FileExampleModel(); $fileModel->filename = $fileName; $fileModel->filepath = $uploadDir . $fileName; $fileModel->filemime = $file['type']; $fileModel->filesize = $file['size']; $fileModel->origname = $file['name']; $fileModel->status = true; if (!$fileModel->save()) { $success = false; break; } // return id from database to link later in the last step $files[] = $fileModel->id; } else { $success = false; } } if ($success === true) { $data = ['success' => $success, 'files' => $files]; } else { $data = ['error' => 'There was an error uploading your files']; } } else { $data = ['success' => $success]; } echo json_encode($data);
ajaxSubmitForm.php
<?php $success = false; $message = null; if (isset($_POST['Model'])) { // example save Model data $model = new ModelExample(); $model->setAttributes($_POST['Model']); $model->validate(); if ($model->save()) { // assign files if we send them by 'filenames' value in the javascript function submitForm if (isset($_POST['filenames'])) { foreach ($_POST['filenames'] as $fileId) { $modelFileRelation = new FileExampleRelationModel(); $modelFileRelation->model_id = $model->id; $modelFileRelation->file_id = $fileId; $modelFileRelation->save(); } } $success = true; $message = 'Form submitted correctly'; } else { // if something go wrong, we should control what to do with the uploaded files $success = false; $message = $model->getErrorMessage(); } } echo json_encode(['success' => $success, 'message' => $message]);
Example to replace domain url
UPDATE your_table SET column_name = REPLACE(column_name, 'old.domain.to.change.com', 'new.domain.com') WHERE column_name LIKE '%old.domain.to.change.com%';
Objective
Make whatever we want before validate and submit a node.
hook_node_validate
/** * hook_node_validate */ function my_module_node_validate($node, $form, &$form_state) { if ($node->type == 'article') { // Check whatever condition with the node content if (!isset($node->body)) { form_set_error('body', t('Body can\'t be empty')); } } }
hook_node_submit
/** * Hook node_submit */ function my_module_node_submit($node, $form, &$form_state) { global $base_url; if ($form['#form_id'] == 'my_content_type_node_form') { // Do whatever before save // ... // Save node node_save($node); // Set message drupal_set_message(t('Content has been submitted correctly.')); // Redirect drupal_goto($base_url . '/my_custom_page'); } }
Objective
Alter form fields of a previously created View called 'Example view'. The system name will be 'example-view'.
Method 1
- In your module, call hook form_alter with the id from the view exposed form
/** * hook form_alter */ function my_module_form_alter(&$form, &$form_state, $form_id) { // Alter view page with system name "example-view" to add a placeholder in the title field if($form['#id'] == "views-exposed-form-example-view-page"){ if (isset($form['title'])) { $form['title']['#size'] = 25; $form['title']['#attributes'] = array('placeholder' => array(t('Search by Name'))); } } }
Method 2
- In your module, call hook views_exposed_form_alter
/** * hook views_exposed_form_alter */ function my_module_views_exposed_form_alter(&$form, $form_state) { // change date format example from a field called 'date_filter' $form['date_filter']['value']['#date_format'] = 'd-m-Y'; }