0

I'm using Magento 2 CE Version 2.1.0.

I'm creating a custom module. For saving data I'm using custom INSERT query.

In that INSERT query, i also need to save URL Key/Identifier which is going to display on Browser URL while user access.

URL Key will be a replica of Post Title. Title Contains Example: Hi Can't Save Dat``a.

if (empty($model->getData('url_key'))) {
    $urlKey = str_replace(" ", "-", strtolower($model->getData('url_key')));
}

$sql = "INSERT INTO `post` (`title`, `url_key`) VALUES ('" . $model->getData('title') . "', '" . $urlKey . "');";
$connection->query($sql);

In URL Key, we have `, `` or any the characters. What can I use as a function, which Magento uses to store product's URL Key in my Custom Module?

So I don't have to write multiple str_replace functions.

Thanks

1

I'm not sure what magento uses internally, but since you are writing insert sql i think you will be fine with any general function. For example this helper function:

protected function _clean($str, $replace = array(), $delimiter = '-')
{
    setlocale(LC_ALL, 'en_US.UTF8');
    if (!empty($replace)) {
        $str = str_replace((array)$replace, ' ', $str);
    }

    $clean = iconv('UTF-8', 'ASCII//TRANSLIT', $str);
    $clean = preg_replace("/[^a-zA-Z0-9\/_|+ -]/", '', $clean);
    $clean = strtolower(trim($clean, '-'));
    $clean = preg_replace("/[\/_|+ -]+/", $delimiter, $clean);

    return $clean;

}

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.