Domanda

Sono nuovo di symfony. Ho deciso di spostare la mia ruota con Symfony versione 2.

Nel mio modulo utente:

  • vorrei convalidare l'unicità della posta elettronica nel database.
  • vorrei anche la password validate con il campo Conferma password.
  • sono riuscito a trovare alcun aiuto nel doc Symfony2.
È stato utile?

Soluzione

Questa roba mi c'è voluto un po 'per rintracciare anche, in modo ecco quello che mi è venuta. A dire il vero io non sono davvero sicuro circa le getRoles () metodo per l'entità utente, ma questa è solo una configurazione di prova per me. elementi di contesto del genere sono forniti esclusivamente per chiarezza.

Ecco alcuni link utili per ulteriori letture:

Ho impostato questo tutto per assicurarsi che ha funzionato come un UserProvider per la sicurezza così da quando ho pensato che erano probabilmente farlo. Ho anche pensato che si stava utilizzando l'e-mail come nome utente, ma non è necessario. Si potrebbe creare un campo nome utente separato e usare quella. Vedere Security per ulteriori informazioni.

Entity (solo le parti importanti; autogenerateable getter / setter sono omesse):

namespace Acme\UserBundle\Entity;

use Symfony\Component\Security\Core\User\UserInterface;
use Symfony\Bridge\Doctrine\Validator\Constraints as DoctrineAssert;
use Doctrine\ORM\Mapping as ORM;

/**
 * @ORM\Entity()
 * @ORM\HasLifecycleCallbacks()
 *
 * list any fields here that must be unique
 * @DoctrineAssert\UniqueEntity(
 *     fields = { "email" }
 * )
 */
class User implements UserInterface
{
    /**
     * @ORM\Id
     * @ORM\Column(type="integer")
     * @ORM\GeneratedValue(strategy="AUTO")
     */
    protected $id;

    /**
     * @ORM\Column(type="string", length="255", unique="true")
     */
    protected $email;

    /**
     * @ORM\Column(type="string", length="128")
     */
    protected $password;

    /**
     * @ORM\Column(type="string", length="5")
     */
    protected $salt;

    /**
     * Create a new User object
     */
    public function __construct() {
        $this->initSalt();
    }

    /**
     * Generate a new salt - can't be done as prepersist because we need it before then
     */
    public function initSalt() {
        $this->salt = substr(str_shuffle(str_repeat('ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789',5)),0,5);
    }

    /**
     * Is the provided user the same as "this"?
     *
     * @return bool
     */
    public function equals(UserInterface $user) {
        if($user->email !== $this->email) {
            return false;
        }

        return true;
    }

    /**
     * Remove sensitive information from the user object
     */
    public function eraseCredentials() {
        $this->password = "";
        $this->salt = "";
    }


    /**
     * Get the list of roles for the user
     *
     * @return string array
     */
    public function getRoles() {
        return array("ROLE_USER");
    }

    /**
     * Get the user's password
     *
     * @return string
     */
    public function getPassword() {
        return $this->password;
    }

    /**
     * Get the user's username
     *
     * We MUST have this to fulfill the requirements of UserInterface
     *
     * @return string
     */
    public function getUsername() {
        return $this->email;
    }

    /**
     * Get the user's "email"
     *
     * @return string
     */
    public function getEmail() {
        return $this->email;
    }

    /**
     * Get the user's salt
     *
     * @return string
     */
    public function getSalt() {
        return $this->salt;
    }

    /**
     * Convert this user to a string representation
     *
     * @return string
     */

    public function __toString() {
        return $this->email;
    }
}
?>

La classe Form:

namespace Acme\UserBundle\Form\Type;

use Symfony\Component\Form\AbstractType;
use Symfony\Component\Form\FormBuilder;

class UserType extends AbstractType {
    public function buildForm(FormBuilder $builder, array $options) {
        $builder->add('email');
        /* this field type lets you show two fields that represent just
           one field in the model and they both must match */
        $builder->add('password', 'repeated', array (
            'type'            => 'password',
            'first_name'      => "Password",
            'second_name'     => "Re-enter Password",
            'invalid_message' => "The passwords don't match!"
        ));
    }

    public function getName() {
        return 'user';
    }

    public function getDefaultOptions(array $options) {
        return array(
            'data_class' => 'Acme\UserBundle\Entity\User',
        );
    }
}
?>

Il controllore:

namespace Acme\UserBundle\Controller;

use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use Symfony\Component\HttpFoundation\Request;
use Acme\UserBundle\Entity\User;
use Acme\UserBundle\Form\Type\UserType;


class userController extends Controller
{
    public function newAction(Request $request) {
        $user = new User();
        $form = $this->createForm(new UserType(), $user);

        if ($request->getMethod() == 'POST') {
            $form->bindRequest($request);

            if ($form->isValid()) {
                // encode the password
                $factory = $this->get('security.encoder_factory');
                $encoder = $factory->getEncoder($user);
                $password = $encoder->encodePassword($user->getPassword(), $user->getSalt());
                $user->setPassword($password);

                $em = $this->getDoctrine()->getEntityManager();
                $em->persist($user);
                $em->flush();

                return $this->redirect($this->generateUrl('AcmeUserBundle_submitNewSuccess'));
            }
        }

        return $this->render('AcmeUserBundle:User:new.html.twig', array (
            'form' => $form->createView()
        ));
    }

    public function submitNewSuccessAction() {
        return $this->render("AcmeUserBundle:User:submitNewSuccess.html.twig");
    }

sezione del security.yml:

security:
    encoders:
        Acme\UserBundle\Entity\User:
            algorithm: sha512
            iterations: 1
            encode_as_base64: true

    role_hierarchy:
        ROLE_ADMIN:       ROLE_USER
        ROLE_SUPER_ADMIN: [ROLE_USER, ROLE_ADMIN, ROLE_ALLOWED_TO_SWITCH]

    providers:
        main:
            entity: { class: Acme\UserBundle\Entity\User, property: email }

    firewalls:
        secured_area:
            pattern:    ^/
            form_login:
                check_path: /login_check
                login_path: /login
            logout:
                path:   /logout
                target: /demo/
            anonymous: ~

Altri suggerimenti

http://github.com/friendsofsymfony c'è un UserBundle che hanno tale funzionalità. È inoltre possibile controllare http://blog.bearwoods.com dove c'è un post su come aggiungere un campo personalizzato, costrizione e validatore per Recaptcha.

risorse thoose dovrebbe iniziare sulla strada giusta se si sta ancora in esecuzione in persone di difficoltà sono generalmente cordiale e disponibile su irc a # symfony-dev sulla rete Freenode. Su Freenoce c'è anche un canale di #symfony generale in cui si possono porre domande su come utilizzare roba dove # symfony-dev è per lo sviluppo di Symfony2 Nucleo.

Speriamo che questo vi aiuterà a spostare in avanti con il progetto.

Penso che la cosa principale che devi guardare fuori per quando si crea il validatore personalizzato è la costante specificata nelle getTargets () metodo.

Se si cambia

self::PROPERTY_CONSTRAINT

a:

self::CLASS_CONSTRAINT

Si dovrebbe essere in grado di accedere a tutte le proprietà del soggetto, non solo una singola proprietà.


. Nota: Se si utilizza le annotazioni per definire i vincoli sarà ora necessario spostare l'annotazione che definisce il vostro validatore fino alla cima della classe come è ora applicabile alla intera entità e non solo la singola proprietà

Si dovrebbe essere in grado di ottenere tutto il necessario dal docs . In particolare le vincoli che contiene informazioni sul controllo e-mail. C'è anche la documentazione sulla scrittura validatori personalizzati .

Ho fatto tutto come su http://symfony.com/doc/2.0 /book/validation.html

Il mio config:

validator.debit_card:
        class: My\Validator\Constraints\DebitCardValidator
        tags:
            - { name: validator.constraint_validator, alias: debit_card }

provato ad usarlo con

@assert:DebitCard
@assert:debitCard
@assert:debit_card

Ma non è attivato?

e-mail univoco dal database

validation.yml

Cruscotto \ ArticleBundle \ Entity \ articolo: vincoli: # - Symfony \ Ponte \ Dottrina \ Validator \ Constraints \ UniqueEntity: SENDEREMAIL - Symfony \ Ponte \ Doctrine \ Validator \ Vincoli \ UniqueEntity: {campi: SENDEREMAIL, un messaggio: Questa email esiste già}

Password con la password di conferma

    $builder->add('password', 'repeated', array(
       'first_name' => 'password',
       'second_name' => 'confirm',
       'type' => 'password',
       'required' => false,
    ));
Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top