Check if slug exists add plus one to the end of the string. using symfony framework

934 views Asked by At

Hi i have a question regarding the slug. Im making a registration system, My problem is how will i able to add the slug plus one?. I was able to check the database if slugname exists, then add plus one here's my code below.

private function saveData($post){
    $repeat_password = sha1($post['repeat_password']);
    $firstName = $post['firstname'];
    $lastName = $post['lastname'];
    $result = $firstName.$lastName;

    $exists = Doctrine_Core::getTable('User')->findOneBySlug($result);
    $i = 1;
    while($exists == true){ 
      $newSlug = $firstName.$lastName.$i;
      //echo $newSlug; exit();

      if($exists == $newSlug){
        $newSlug = $firstName.$lastName.$i++;
        //echo $newSlug; exit();

      }
    }

    $register = new User();
    $register->setFirstName($post['firstname']);
    $register->setLastName($post['lastname']);
    $register->setEmail($post['repeat_email']);
    $register->setPassword($repeat_password);
    $register->setSlug($result);  
    $register->save();

    $passwordReminder = new PasswordReminder();
    $passwordReminder->setEmail($post['repeat_email']);
    $passwordReminder->setHash(md5(md5(time())));
    $passwordReminder->save();



    return $register->getId();


  }

How will i able to get the value of the slug? and insert it here?

$exists = Doctrine_Core::getTable('User')->findOneBySlug($result);
    $i = 1;
    while($exists == true){ 
      $newSlug = $firstName.$lastName.$i;
      //echo $newSlug; exit();

      if($exists == $newSlug){
        $newSlug = $firstName.$lastName.$i++;
        //echo $newSlug; exit();

      }
    }

Ive been in this problem for a week now, can someone help me? out in this? thanks

1

There are 1 answers

0
nikolajosipovic On

You can use l3pp4rd/DoctrineExtensions and the Sluggable behavior which solves that for you.

Sluggable behavior manual: https://github.com/l3pp4rd/DoctrineExtensions/blob/master/doc/sluggable.md

Ready to use bundle for Symfony2: https://github.com/stof/StofDoctrineExtensionsBundle