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

ercv8c1e  于 2021-06-20  发布在  Mysql
关注(0)|答案(0)|浏览(207)

我是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()) 完全。请帮助,我没有发现任何错误,也没有抛出错误或异常。
编辑:因为你要求安全.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语句中运行检查 if($form->isSubmitted() or 1) 它说我试图在数据库中的字段中插入空值,这是必需的。请帮忙。一些 var_dump($form->getErrors()); (无法发布整个内容,因为即使是pastebin也会说它太长,并在请求中给出错误):
https://pastebin.com/7yb9cicg

暂无答案!

目前还没有任何答案,快来回答吧!

相关问题