带有FOSUserBundle和RestUserBundle的Symfony2注册API:表单提交不起作用

时间:2015-08-26 12:48:55

标签: php ajax rest symfony

我试图让用户使用rest api注册到系统。 我试过很多方面,但每次我的控制器说(没有理由:它没有告诉我任何错误)表格无效。

所以,在这里我的代码可以更好地理解我正在做的事情。

user.php的

use FOS\UserBundle\Entity\User as BaseUser;
use Doctrine\ORM\Mapping as ORM;
use Symfony\Component\HttpFoundation\File\UploadedFile;
use Symfony\Component\Validator\Constraints as Assert;
use Symfony\Component\Security\Core\Util\SecureRandom;
use JMS\Serializer\Annotation\ExclusionPolicy;
use JMS\Serializer\Annotation\Expose;
use JMS\Serializer\Annotation\Groups;
use JMS\Serializer\Annotation\VirtualProperty;

/**
 * @ORM\Entity
 * @ORM\HasLifecycleCallbacks()
 * @ORM\Table(name="User")
 * @ExclusionPolicy("all")
 */
class User extends BaseUser
{
/**
 * @ORM\Id
 * @ORM\Column(type="integer")
 * @ORM\GeneratedValue(strategy="AUTO")
 */
protected $id;

/**
 * @var string
 * @ORM\Column(type="string", nullable=true)
 * @Expose
 */
protected $FBId;

/**
 * @ORM\ManyToMany(targetEntity="User", mappedBy="myFriends")
 **/
protected $friendsWithMe;

/**
 * @ORM\Column(type="string",length=255,nullable=true)
 * @Assert\Length(
 *     min=3,
 *     max=255,
 *     minMessage="The name is too short.",
 *     maxMessage="The name is too long.",
 *     groups={"Registration", "Profile"}
 * )
 * @Expose
 */
protected $name;

/**
 * @ORM\Column(type="string",length=255,nullable=true)
 * @Assert\Length(
 *     min=3,
 *     max=255,
 *     minMessage="The surname is too short.",
 *     maxMessage="The surname is too long.",
 *     groups={"Registration", "Profile"}
 * )
 * @Expose
 */
protected $surname;

/**
 * @ORM\Column(type="datetime")
 * @Expose
 */
protected $registrationDate;


/**
 * @Assert\Choice(
 *     choices = { "M", "F" },
 *     message = "Invalid gender."
 * )
 * @ORM\Column(type="string",length=2)
 * @Assert\NotBlank(message="Please enter your gender.", groups={"Registration", "Profile"})
 * @Expose
 */
protected $gender;

/**
 * @ORM\Column(type="date")
 * @Assert\NotBlank(message="Please enter your birth's date.", groups={"Registration", "Profile"})
 * @Expose
 */
protected $birth;

public function __construct()
{
    $this->myFriends = new \Doctrine\Common\Collections\ArrayCollection();
 }

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

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

    return $this;
}

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

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

    return $this;
}

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

/**
 * Set registrationDate
 *
 * @param \DateTime $registrationDate
 * @return User
 */
public function setRegistrationDate($registrationDate)
{
    $this->registrationDate = $registrationDate;

    return $this;
}

/**
 * Get registrationDate
 *
 * @return \DateTime
 */
public function getRegistrationDate()
{
    return $this->registrationDate;
}


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

    return $this;
}

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

/**
 * Set birth
 *
 * @param \DateTime $birth
 * @return User
 */
public function setBirth($birth)
{
    $this->birth = $birth;

    return $this;
}

/**
 * Get birth
 *
 * @return \DateTime
 */
public function getBirth()
{
    return $this->birth;
}

/**
 * @ORM\PrePersist()
 * Write a correct date on DB
 */

public function prePersist()
{
    $this->registrationDate = new \DateTime();

}

}


/**
 * Set FBId
 *
 * @param string $fBId
 * @return User
 */
public function setFBId($fBId)
{
    $this->FBId = $fBId;

    return $this;
}

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

}

RegistrationFormType.php

use Symfony\Component\Form\AbstractType;
use Symfony\Component\Form\FormBuilderInterface;
use Symfony\Component\DependencyInjection\Container;
use Symfony\Component\OptionsResolver\OptionsResolver;

class RegistrationFormType extends AbstractType{

public function buildForm(FormBuilderInterface $builder, array $options)
{
        $builder->add('name');
        $builder->add('surname');
        $builder->add('gender', 'choice', array('choices' => array('M' => 'Male', 'F' => 'Female')));
        $builder->add('birth', 'birthday');

}

public function configureOptions(OptionsResolver $resolver)
{

    $resolver->setDefaults(array(
        'data_class' => '\Entity\User',
        'csrf_protection' => false
    ));

}

public function getParent()
{
    return 'fos_user_registration';
}

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

}

UserRestController.php

use UserBundle\Form\RestRegistrationFormType;
use UserBundle\Form\Type\RegistrationFormType;
use FOS\RestBundle\Controller\Annotations\View;
use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use Symfony\Component\Security\Core\Exception\AccessDeniedException;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Route;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Template;
use Symfony\Component\HttpFoundation\Request;
use Entity\User as User;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Method;

class UserRestController extends Controller
{

/**
 * @Template(engine="serializer")
 */
public function getUserRegistrationAction(Request $request){
    return $this->processForm(new User(), $request);
}

private function processForm(User $user, Request $request) {

    $form = $this->createForm(new RegistrationFormType(), $user);
    $form->handleRequest($request);
    if ($form->isValid()) {
        $data = $form->getData();

        $user = new User();
        $user->setEmail($data['email']);
        $user->setPassword($this->encodePassword($user, $data['password']));
        $user->setGender($data['gender']);
        $user->setBirth($data['birth']);
        $em = $this->getDoctrine()->getManager();
        $em->persist($user);
        $em->flush();

        $response = new Response();
        $response->setStatusCode($statusCode);

        return $response;
    }

        print_r($this->getErrorMessages($form));


    return \FOS\RestBundle\View\View::create($form, 400);
    return View::create($form, 400);
}

private function getErrorMessages(\Symfony\Component\Form\Form $form)
{
    $errors = array();

    if ($form->count() > 0) {
        foreach ($form->all() as $child) {
            /**
             * @var \Symfony\Component\Form\Form $child
             */
            if (!$child->isValid()) {
                $errors[$child->getName()] = $this->getErrorMessages($child);
            }
        }
    } else {
        /**
         * @var \Symfony\Component\Form\FormError $error
         */
        foreach ($form->getErrors() as $key => $error) {
            $errors[] = $error->getMessage();
        }
    }

    return $errors;
}
}

因此,在控制器中,if($ form-> isValid())返回false。 我收到的输出是 - 例如 - localhost:8000 / api / user / registration.json?username = p& email = mymail%40test.com& plainPassword = qwe& birth = 1970-11- 11& gender = M& name = fooname& surname = foosurname (这是我的ajax调用的请求)是:

Array
(
[username] => Array
    (
    )

[email] => Array
    (
    )

[plainPassword] => Array
    (
        [first] => Array
            (
            )

        [second] => Array
            (
            )

    )

[name] => Array
    (
    )

[surname] => Array
    (
    )

[gender] => Array
    (
    )

[birth] => Array
    (
        [year] => Array
            (
            )

        [month] => Array
            (
            )

        [day] => Array
            (
            )

    )

)     { “孩子”:{ “用户名”:{}, “电子邮件”:{}, “plainPassword”:{ “孩子”:{ “第一”:{}, “第二”:{}}}, “名”: {}, “姓”:{}, “性别”:{}, “诞生”:{ “孩子”:{ “年”:{}, “月”:{}, “天”:{}}}} }

注意:我只使用GET方法进行测试,但使用POST方法则相同。

0 个答案:

没有答案