Slugify a string from the object data input (no classes just js)

PHOTO EMBED

Sat Nov 05 2022 09:39:40 GMT+0000 (Coordinated Universal Time)

Saved by @swina #javascript #pimcore

//create a button (layout component) in the object class

//example you want to create a slug based on a field name 'title' (text input)
//to save in the field 'url' (text input)
//click on the button will automatically create the slug

//copy and paste the following code in the button handler
((btn)=>{

//get button id
const id = btn.id
//get button element
const button = document.getElementById(id);
//define the current DataObject as workspace in order to find the elements  
const workspace = '_data_object_name'; //ex. News
  
//find the root element of the record
const root = button.closest('div.pimcore_class_' + workspace);

//find the source input field by name with the value to slugify (in this example 'title')
const source = root.querySelector('input[name="title"]');
//find the targe input field by name with the slugified value (in this example 'url')  
const target = root.querySelector('input[name="url"]');

//set the target value with the slugified value
target.value = slugify(source.value);

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

    // Make the string lowercase
    str = str.toLowerCase();

    // Remove accents, swap ñ for n, etc
    var from = "ÁÄÂÀÃÅČÇĆĎÉĚËÈÊẼĔȆÍÌÎÏŇÑÓÖÒÔÕØŘŔŠŤÚŮÜÙÛÝŸŽáäâàãåčçćďéěëèêẽĕȇíìîïňñóöòôõøðřŕšťúůüùûýÿžþÞĐđßÆa·/_,:;";
    var to   = "AAAAAACCCDEEEEEEEEIIIINNOOOOOORRSTUUUUUYYZaaaaaacccdeeeeeeeeiiiinnooooooorrstuuuuuyyzbBDdBAa------";
    for (var i=0, l=from.length ; i<l ; i++) {
        str = str.replace(new RegExp(from.charAt(i), 'g'), to.charAt(i));
    }

    // Remove invalid chars
    str = str.replace(/[^a-z0-9 -]/g, '') 
    // Collapse whitespace and replace by -
    .replace(/\s+/g, '-') 
    // Collapse dashes
    .replace(/-+/g, '-'); 

    return str;
}
});
content_copyCOPY