This topic is locked

Create "slug" field Before Add and "on the fly"

4/3/2020 12:24:12 AM
PHPRunner General questions
A
alfonso authorDevClub member

I try to explain myself. I have multiple tables in the project that have a field called "name" or "title". I want to automatically populate another field that has each table called "slug" optimized for friendly urls
For example:

  • "name" field: "Tomorrow, I will be in class soon!", It should return
  • "slug" field: "tomorrow-I'll-be-in-class-soon"
    I have managed to do this by creating a function that we have added in Add Page-> Before record added and in Edit Page-> Before record uodated



$separador = '-';//ejemplo utilizado con guión medio

$originales = 'ÀÁÂÃÄÅÆÇÈÉÊËÌÍÎÏÐÑÒÓÔÕÖØÙÚÛÜÝÞßà áâãäåæçèéêëìíîïðñòóôõöøùúûýýþÿŔŕ';

$modificadas = 'aaaaaaaceeeeiiiidnoooooouuuuybsaaaaaaaceeeeiiiidnoooooouuuyybyRr';
//Quitamos todos los posibles acentos

$url = strtr(utf8_decode($values['name']), utf8_decode($originales), $modificadas);
//Convertimos la cadena a minusculas

$url = utf8_encode(strtolower($url));
//Quitamos los saltos de linea y cuanquier caracter especial

$buscar = array(' ', '&', '\r\n', '\n', '+');

$url = str_replace ($buscar, $separador, $url);

$buscar = array('/[^a-z0-9\-<>]/', '/[\-]+/', '/<[^>]*>/');

$reemplazar = array('', $separador, '');

$url = preg_replace ($buscar, $reemplazar, $url);
$values['slug']=$url;


My questions are:

  1. Do I have to put the same code in all the events of all the tables?
  2. Can you create a global function and then call it on each event? How is it done?
  3. The result of this function is only seen when the information is saved. Can you see online how the "slug" field is being filled as we write in the "name" or "title" field?
    Thank you

C
cristi 4/3/2020

You don't need PHP to do that..

You could do it in MySQL if that is the database server that you use...-can be adapted to other database engines

Take a look HERE or HERE
If you want "on the fly" capabilities it can be done in JavaScript (adapt on your special characters based on localization, etc) - in the "onload" event

str = str.replace(/^\s+|\s+$/g, ''); // trim

str = str.toLowerCase();
// remove accents, swap ñ for n, etc

var from = "àáäâèéëêìíïîòóöôùúüûñç·/_,:;";

var to = "aaaaeeeeiiiioooouuuunc------";
for (var i=0, l=from.length ; i<l ; i++)

str = str.replace(new RegExp(from.charAt(i), 'g'), to.charAt(i));
str = str.replace(/[^a-z0-9 -]/g, '') // remove invalid chars

.replace(/\s+/g, '-') // collapse whitespace and replace by -

.replace(/-+/g, '-'); // collapse dashes
return str;


Original post HERE
Or...you could use a readily available library HERE