表单已提交,但是我没有在数据库中得到结果

时间:2018-08-24 20:26:40

标签: php mysql symfony symfony-3.4

我是Symfony的新手,在向数据库提交包含数据的表单时遇到问题。因此,我完成了链接,但是以某种方式,逻辑无法理解我提交了表单。 这是我的控制器,我在其中检查是否已提交并加密密码:

    use AppBundle\Entity\UserLogin;
use AppBundle\Form\UserType;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Method;//removed it because it says it is depricated in 3.4
use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\Routing\Annotation\Route;



class SecurityController extends Controller
{
    /**
     * @Route("/login", name="sec_login")
     * @Method("POST")//removed it, because I do not use the namespace anymore
     * @return \Symfony\Component\HttpFoundation\Response
     */
    public function loginAction(){
        return $this->render("default/index.html.twig");
    }

    /**
     * @Route("/register", name="sec_register")
     * @Method("POST")
     * @param Request $request
     * @return \Symfony\Component\HttpFoundation\Response
     */
    public function registerAction(Request $request){
        $user = new UserLogin();
        $form = $this->createForm(UserType::class, $user);
        $form->handleRequest($request);
        if($form->isSubmitted() && $form->isValid()){
            $password = $this->get("security.password_encoder")
                ->encodePassword($user, $user->getPassword());

            $user->setPassword($password);
            print_r('here');
            $em = $this->getDoctrine()->getManager();
            $em->persist($user);
            $em->flush();
            return $this->redirectToRoute("sec_login", array('form'=>$form->createView()));
        }
        var_dump($user);
        return $this->render("default/index.html.twig");
    }

    /**
     * @Route("/profile", name="user_profile")
     */
    public function profileAction(){
        return $this->render('default/profile.html.twig');
    }
}

我的数据库实体:

 <?php

namespace AppBundle\Entity;

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

/**
 * Userlogin
 *
 * @ORM\Table(name="user_login")
 * @ORM\Entity(repositoryClass="AppBundle\Repository\UserLoginRepository")
 */
class UserLogin implements UserInterface
{
    /**
     * @var int
     *
     * @ORM\Column(name="id", type="integer")
     * @ORM\Id
     * @ORM\GeneratedValue(strategy="AUTO")
     */
    private $id;

    /**
     * @var string
     * @Assert\NotBlank()
     * @ORM\Column(name="username", type="string", length=20, unique=true)
     */
    private $username;

    /**
     * @var string
     * @Assert\NotBlank()
     * @Assert\Type("\email")
     * @ORM\Column(name="email", type="string", length=20, unique=true)
     */
    private $email;

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


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

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

        return $this;
    }

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

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

        return $this;
    }

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

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

        return $this;
    }

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

    /**
     * Returns the roles granted to the user.
     *
     * <code>
     * public function getRoles()
     * {
     *     return array('ROLE_USER');
     * }
     * </code>
     *
     * Alternatively, the roles might be stored on a ``roles`` property,
     * and populated in any number of different ways when the user object
     * is created.
     *
     * @return (Role|string)[] The user roles
     */
    public function getRoles()
    {
        // TODO: Implement getRoles() method.
        return [];
    }

    /**
     * Returns the salt that was originally used to encode the password.
     *
     * This can return null if the password was not encoded using a salt.
     *
     * @return string|null The salt
     */
    public function getSalt()
    {
        // TODO: Implement getSalt() method.
    }

    /**
     * Removes sensitive data from the user.
     *
     * This is important if, at any given point, sensitive information like
     * the plain-text password is stored on this object.
     */
    public function eraseCredentials()
    {
        // TODO: Implement eraseCredentials() method.
    }
}

和表格:

 <?php

namespace AppBundle\Form;

use AppBundle\Entity\UserLogin;
use Symfony\Component\Form\AbstractType;
use Symfony\Component\Form\Extension\Core\Type\EmailType;
use Symfony\Component\Form\Extension\Core\Type\PasswordType;
use Symfony\Component\Form\Extension\Core\Type\SubmitType;
use Symfony\Component\Form\Extension\Core\Type\TextType;
use Symfony\Component\Form\FormBuilderInterface;
use Symfony\Component\OptionsResolver\OptionsResolver;

class UserType extends AbstractType
{
    public function buildForm(FormBuilderInterface $builder, array $options)
    {
        $builder->add("username", TextType::class)
            ->add("email", EmailType::class)
            ->add("password", PasswordType::class)
            ->add("registered", SubmitType::class);
    }

    public function configureOptions(OptionsResolver $resolver)
    {
        $resolver->setDefaults(array("data_class" => UserLogin::class));
    }

    public function getBlockPrefix()//removed that, because some people suggested that this might cause problems
    {
        return 'app_bundle_user_type';
    }
}

我的模板是:

{% extends 'base.html.twig' %}


{% block stylesheets %}
<link rel="stylesheet" href="{{ asset('/css/indexStyle.css') }}">
{% endblock %}

{% block body %}
        <div class="navbar" id="heading">
            <span id="wepart">We</span><span id="conpart">Connect</span>
            <span ><a href="#" class="logger" onclick="expandFunc('login')">Login</a></span>
            <span ><a href="#" class="logger" onclick="expandFunc('register')">Register</a></span>//replaced a href with button, because it was adding # after register in the url
        </div>
        <div id="main">

        <div id="register">
            <form action="{{ path('sec_register') }}" method="post" name="sec_register">

                <input type="text" name="userlogin[username]" placeholder="Username..." /><br/>
                <input type="password" name="userlogin[password]" placeholder="Password..." /><br/>
                <!--<input type="text" name="passwordRe" /><br/>-->
                <input type="email" name="userlogin[email]" placeholder="Email..." /><br/>
                <input type="hidden" name="_crsf_token">
                <input type="submit" name="userlogin[registered]" class="btn btn-light btn-block" value="Sign up" /><br/>

            </form>
        </div>

        <div id="login">
            <form action="{{ path('sec_login') }}" method="post">

                <input type="text" name="_username" placeholder="Username..." onfocus="value='Type username here.'" value="" /><br/>
                <input type="password" name="_password" placeholder="Password..." /><br/>
                <input type="submit" name="logged" class="btn btn-light btn-block" value="Sign in" /><br/>

            </form>
        </div>


ha




        </div>


{% endblock %}
{% block javascripts %}
    <script rel="script" src="{{ asset('/js/indexJavascript.js') }}"></script>
{% endblock %}

提交表单时,数据库中没有数据,var_dump($user)的属性为NULL。我根本不参与if($form->isSubmitted() && $form->isValid())。请帮忙,我没有发现任何错误,也没有抛出任何错误或异常。
编辑: 因为您要求输入security.yml。就是这样:

# To get started with security, check out the documentation:
# https://symfony.com/doc/current/security.html
security:
    encoders:
        # Our user class and the algorithm we&#39;ll use to encode passwords
        AppBundle\Entity\UserLogin: bcrypt

    # https://symfony.com/doc/current/security.html#b-configuring-how-users-are-loaded
    providers:

        database_users:
          entity: { class: AppBundle:Userlogin, property: email }

        in_memory:
            memory: ~

    firewalls:
        # disables authentication for assets and the profiler, adapt it according to your needs
        dev:
            pattern: ^/(_(profiler|wdt)|css|images|js)/
            security: false

        main:
            anonymous: ~
            # activate different ways to authenticate

            # https://symfony.com/doc/current/security.html#a-configuring-how-your-users-will-authenticate
            #http_basic: ~

            # https://symfony.com/doc/current/security/form_login_setup.html
            #form_login: ~
            form_login:
                check_path: sec_login

                login_path: sec_login
    #access_control:
    #    - { path: ^\register, roles: IS_AUTHENTICATED_ANONIMOUSLY }

但老实说,问题出在注册表上。而且我认为这可能与您看到的两个表单都在一页中有关。表单根本没有提交,但是我提交了。在添加if($form->isSubmitted() or 1)的if语句中进行检查,并说我正在尝试在数据库的字段中插入必填的空值。请帮忙。 var_dump($form->getErrors());中的某些内容(无法粘贴整个内容,因为甚至pastebin都说它太长了,并在请求中给出了错误):

https://pastebin.com/7YB9CicG

0 个答案:

没有答案