错误:在数组上调用成员函数setPassword()

时间:2015-08-20 01:14:01

标签: php forms symfony

我的Symfony应用程序中的新用户注册表有问题。我首先在控制器中创建了表单并且它正常工作,但是当将表单移动到RegisterFormType.php时,我开始面对标题中所说的问题,当我试图保存用户时。

以下是表单类:

namespace SF2\UserBundle\Form;

use Symfony\Component\Form\AbstractType;
use Symfony\Component\Form\FormBuilderInterface;

class RegisterFormType extends AbstractType
{
    public function buildForm(FormBuilderInterface $builder, array $options)
    {
        $builder
            ->add(
                'username', 'text', array(
                    'pattern' => '[a-zA-Z0-9]+',
                    'attr' => array(
                        'class' => 'form-control'
                    )
                )
            )

            ->add(
                'plainPassword', 'repeated', array(
                    'type' => 'password',
                    'first_options' => array(
                        'label' => 'Password'
                    ),
                    'second_options' => array(
                        'label' => 'Repeat Password'
                    ),
                    'options' => array(
                        'attr' => array(
                            'class' => 'form-control'
                        )
                    )
                )
            )

            ->add(
                'email', 'email', array(
                    'attr' => array(
                        'class' => 'form-control'
                    )
                )
            );
    }

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

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

下一课是处理注册过程的控制器

namespace SF2\UserBundle\Controller;

use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use Symfony\Component\HttpFoundation\Request;
use SF2\UserBundle\Form\RegisterFormType;

class RegisterController extends Controller
{
    public function registerAction(Request $request)
    {
        $form = $this->createForm(new RegisterFormType());

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

            if ($form->isValid()) {
                $user = $form->getData();
                $user->setPassword($this->encodePassword($user, $user->getPlainPassword()));

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

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

        return $this->render('UserBundle:Register:register.html.twig', array(
            'form' => $form->createView()
        ));
    }

    public function encodePassword($user, $plainPassword)
    {
        $encoder = $this->container->get('security.encoder_factory')
                                   ->getEncoder($user);

        return $encoder->encodePassword($plainPassword, $user->getSalt());
    }
}

实体用户:

namespace SF2\UserBundle\Entity;

use Doctrine\ORM\Mapping as ORM;
use Symfony\Component\Security\Core\User\UserInterface;
use Symfony\Component\Security\Core\User\AdvancedUserInterface;
use Serializable;
use Symfony\Component\Validator\Constraints as Assert;

/**
 * User
 *
 * @ORM\Table()
 * @ORM\Entity(repositoryClass="SF2\UserBundle\Entity\UserRepository")
 */
class User implements AdvancedUserInterface
{
    /**
     * @var integer
     *
     * @ORM\Column(name="id", type="integer")
     * @ORM\Id
     * @ORM\GeneratedValue(strategy="AUTO")
     */
    private $id;

    /**
     * @var string
     *
     * @ORM\Column(name="username", type="string", length=255)
     * @Assert\NotBlank(message="Enter an username")
     */
    private $username;

    /**
     * @var string
     *
     * @Assert\NotBlank()
     * @ORM\Column(name="password", type="string", length=255)
     */
    private $password;

    /**
     * @var string
     *
     * @ORM\Column(name="salt", type="string", length=255)
     */
    private $salt;

    /**
     * @var array
     * 
     * @ORM\Column(type="array")
     */
    private $roles = array();

    /**
     * @var bool
     * 
     * @ORM\Column(type="boolean")
     */
    private $isActive = true;

    /**
     * @var string
     * 
     * @ORM\Column(type="string", length=255)
     * @Assert\NotBlank()
     * @Assert\Email()
     */
    private $email;

    /**
     *
     * @var string
     */
    private $plainPassword;

    public function __construct()
    {
        $this->salt = base_convert(sha1(uniqid(mt_rand(), true)), 16, 36);
    }

    /**
     * Get id
     *
     * @return integer 
     */
    public function getId()
    {
        return $this->id;
    }

    /**
     * Set username
     *
     * @param string $username
     * @return User
     */
    public function setUsername($username)
    {
        $this->username = $username;

        return $this;
    }

    /**
     * Get username
     *
     * @return string 
     */
    public function getUsername()
    {
        return $this->username;
    }

    /**
     * Set password
     *
     * @param string $password
     * @return User
     */
    public function setPassword($password)
    {
        $this->password = $password;

        return $this;
    }

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

    /**
     * Set salt
     *
     * @param string $salt
     * @return User
     */
    public function setSalt($salt)
    {
        $this->salt = $salt;

        return $this;
    }

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

    /**
     * Set user's roles
     * 
     * @param type $roles
     * @return type
     */
    public function setRoles(array $roles)
    {
        $this->roles = $roles;
    }

    /**
     * Get roles.
     * Sets default role as regular user
     * 
     * @return Array
     */
    public function getRoles()
    {
        $roles = $this->roles;
        $roles[] = 'ROLE_USER';

        return array_unique($roles);
    }

    /**
     * Set user's status
     * 
     * @param type $isActive
     */
    function setIsActive($isActive)
    {
        $this->isActive = $isActive;
    }

    /**
     * Get user's status
     * 
     * @return bool
     */
    function getIsActive()
    {
        return $this->isActive;
    }

    /**
     * Set email
     *
     * @param string $email
     * @return User
     */
    public function setEmail($email)
    {
        $this->email = $email;

        return $this;
    }

    /**
     * Get email
     *
     * @return string 
     */
    public function getEmail()
    {
        return $this->email;
    }

    /**
     * Set plainPassword
     * 
     * @param type $plainPassword
     */
    function setPlainPassword($plainPassword)
    {
        $this->plainPassword = $plainPassword;
    }

    /**
     * Get plainPassword
     * 
     * @return string
     */
    function getPlainPassword()
    {
        return $this->plainPassword;
    }

    /**
     * Compares the user ID
     * 
     * @param UserInterface $user
     * @return boolean
     */
    public function equals(UserInterface $user)
    {
        return $this->getId() == $user->getId();
    }

    public function eraseCredentials()
    {
        $this->setPassword(null);
    }

    public function isAccountNonExpired()
    {
        return true;
    }

    public function isAccountNonLocked()
    {
        return true;
    }

    public function isCredentialsNonExpired()
    {
        return true;
    }

    public function isEnabled()
    {
        return $this->getIsActive();
    }

    public function serialize()
    {
        return serialize(array(
            'id' => $this->getId()
        ));
    }

    public function unserialize($serialized)
    {
        $data = unserialize($serialized);
        $this->id = $data['id'];
    }

}

Symfony的堆栈跟踪将错误指向此行:$user->setPassword($this->encodePassword($user, $user->getPlainPassword()));

我想显示此代码就足够了,但请随意在github

中查看

深深感激。

3 个答案:

答案 0 :(得分:0)

您的表单类型不处理User类,因为您没有设置该类,这就是$form->getData()返回数组而不是对象User的原因。

在formType中添加:

use Symfony\Component\OptionsResolver\OptionsResolverInterface;

...

public function setDefaultOptions(OptionsResolverInterface $resolver)
    {
        $resolver->setDefaults(array(
            'data_class' => 'SF2\UserBundle\Entity\User',
        ));
    }

答案 1 :(得分:0)

public function getDefaultOptions()
{
   return function (OptionsResolverInterface $resolver) {

             return $resolver->setDefaults(array(
             'data_class' => 'SF2\UserBundle\Entity\User'
             ));         

         }
}

现在不推荐使用getDefaultOptions,它不使用$ options参数,这里建议使用闭包。我知道你使用的是旧版本的symfony所以试试这个看看,这个代码是我未经测试的,因为我没有旧版本

答案 2 :(得分:0)

基于这两个答案,我可以知道要搜索什么,我找到了解决方案:

public function configureOptions(OptionsResolver $resolver)
{
    $resolver->setDefaults(array(
        'data_class' => 'SF2\UserBundle\Entity\User'
    ));
}

使用configureOptions代替setDefaultOptions

赞赏。