http://box365.in/generar-enlaces-permanentes-en-cakephp/
  • Tecnología / Webmaster

Generar enlaces permanentes en CakePHP (Slug)


microsoft-one-drive

Código útil para generar enlaces permanentes en CakePHP. éstas simples líneas te permitirán generar los “slugs” automáticamente (se sobre entiende que las tablas trabajan con las columnas name y slug).

Agrega este codigo en: app/Model/AppModel.php

/**
* This method generates a slug from a title
*
* @param  string $title The title or name
* @param  string $id The ID of the model
* @return string Slug
*/
    public function generateSlug($title = null, $id = null) {
        if (!$title) {
            throw new NotFoundException(__('Invalid Title'));
        }

        $title = strtolower($title);
        $slug  = Inflector::slug($title, '-');

        $conditions = array();
        $conditions[$this->alias . '.slug'] = $slug;

        if ($id) {
            $conditions[$this->primaryKey. ' NOT'] = $id;
        }

        $total = $this->find('count', array('conditions' => $conditions, 'recursive' => -1));
        if ($total > 0) {
            for ($number = 2; $number > 0; $number ++) {
                $conditions[$this->alias . '.slug'] = $slug . '-' . $number;

                $total = $this->find('count', array('conditions' => $conditions, 'recursive' => -1));
                if ($total == 0) {
                    return $slug . '-' . $number;
                }
            }
        }

        return $slug;
    }

Agrega estas otras líneas en tu modelo Ej: app/Model/Article.php

/**
 * Overrides parent before save for slug generation
 * Also handles ordering of the page
 *
 * @return boolean Always true
 */
    public function beforeSave($options = array()) {
        if (!empty($this->data[$this->alias]['title']) && empty($this->data[$this->alias]['slug'])) {
            if (!empty($this->data[$this->alias][$this->primaryKey])) {
                $this->data[$this->alias]['slug'] = $this->generateSlug($this->data[$this->alias]['title'], $this->data['Article'][$this->primaryKey]);
            } else {
                $this->data[$this->alias]['slug'] = $this->generateSlug($this->data[$this->alias]['title']);
            }
        }

        return true;
    }

Relacionados...