dos8410 2018-03-12 22:23
浏览 41
已采纳

在控制器symfony3中以一对一的关系自动设置关系值

A little background information. I have two entities that have a Bidirectional relationship: essentially, an application form can have exactly one recommendation form. When a recommender fills out a form, I would like to have it automatically, and only select the related application form (protect other user's data), based on a specific code, which they enter on a custom formpage I created. I'm not sure how it happened, but I got it to work once, but for some unknown reason, it stopped and is adding "NULL" for the applicant form id in the recommendation form in my database. I'll include all info that I can:

RecommendationForm Entity:

namespace AppBundle\Entity;

use Doctrine\ORM\Mapping as ORM;

/**
 * RecommendationForm
 *
 * @ORM\Table(name="recommendation_form")
 * @ORM\Entity(repositoryClass="AppBundle\Repository\RecommendationFormRepository")
 */
class RecommendationForm
{
    /**
     * @var int
     *
     * @ORM\Column(name="id", type="integer")
     * @ORM\Id
     * @ORM\GeneratedValue(strategy="AUTO")
     */
    private $id;

    /**
     * One RecommendationForm has One ApplicantForm.
     * @ORM\OneToOne(targetEntity="ApplicantForm", inversedBy="recommendation_form")
     * @ORM\JoinColumn(name="applicant_form_id", referencedColumnName="id")
     */
    private $applicant_form;

    //....

    public function __construct($applicant_form) {
        date_default_timezone_set('America/New_York');

        $this->applicant_form = $applicant_form;

        $this->submitDate = new \DateTime("now");
    }


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


    // /**
    //  * Set applicantForm
    //  *
    //  * @param integer $applicant_form
    //  *
    //  * @return RecommendationForm
    //  */
    // public function setApplicantForm($applicant_form)
    // {
    //     $this->applicant_form = $applicant_form;

    //     return $this;
    // }

    /**
     * Get applicantForm
     *
     * @return integer
     */
    public function getApplicantForm()
    {
        return $this->applicant_form;
    }

//....
}

ApplicantForm Entity:

namespace AppBundle\Entity;

use Doctrine\ORM\Mapping as ORM;
use chriskacerguis\Randomstring\Randomstring;

/**
 * ApplicantForm
 *
 * @ORM\Table(name="applicant_form")
 * @ORM\Entity(repositoryClass="AppBundle\Repository\ApplicantFormRepository")
 */
class ApplicantForm
{
    /**
     * @var int
     *
     * @ORM\Column(name="id", type="integer")
     * @ORM\Id
     * @ORM\GeneratedValue(strategy="AUTO")
     */
    private $id;

    /**
     * One ApplicantForm has One RecommendationForm.
     * @ORM\OneToOne(targetEntity="RecommendationForm", mappedBy="applicant_form")
     */
    private $recommendation_form;

    /**
     * @var string
     *
     * @ORM\Column(name="accessCode", type="string", length=75, unique=true)
     */
    private $accessCode;

    //....

    public function __construct() {

        $random = new \chriskacerguis\Randomstring\Randomstring();

        $this->accessCode = $random->generate(15, true);
    }

//...
}

RecommendationController:

namespace AppBundle\Controller;

use AppBundle\Entity\RecommendationForm;
use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Method;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Route;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\Form\Extension\Core\Type\EmailType;
use Symfony\Component\Form\Extension\Core\Type\PasswordType;
use Symfony\Component\Form\Extension\Core\Type\SubmitType;

/**
 * Recommendationform controller.
 *
 * @Route("recommendationform")
 */
class RecommendationFormController extends Controller
{
    private $accessCode;
    private $applicantForm;
    private $applicantFormID;
    /**
     * Lists all RecommendationForm entities.
     *
     * @Route("/", name="recommendationform_index")
     * @Method({"GET", "POST"})
     */
    public function indexAction(Request $request)
    {
        $em = $this->getDoctrine()->getManager();

        $data = array();
        $form = $this->createFormBuilder($data)
            ->add('email', EmailType::class)
            ->add('accessCodeSS', PasswordType::class)
            ->add('submit', SubmitType::class)
            ->getForm();

        $form->handleRequest($request);

        if ($form->isSubmitted() && $form->isValid()) {
            $accessCode = $form["accessCodeSS"]->getData();

            return $this->redirectToRoute('recommendationform_new');
        }

        return $this->render('recommendationform/index.html.twig', array(
                'form' => $form->createView(),
        ));
    }

    /**
     * Creates a new RecommendationForm entity.
     *
     * @Route("/new", name="recommendationform_new")
     * @Method({"GET", "POST"})
     */
    public function newAction(Request $request)
    {
        if(isset($_POST["accessCodeSS"])){

            $this->accessCode = $_POST["accessCodeSS"];

            $accessCode = $this->accessCode;
            $em = $this->getDoctrine()->getManager();

            $query = $em->createQuery('SELECT u FROM AppBundle:ApplicantForm u WHERE u.accessCode = :accessCode')
                ->setParameter('accessCode', $accessCode);
            $applicantFormID = $query->getResult();

            $this->applicantForm = $applicantFormID[0];

        }

        var_dump($this->applicantForm);

        $RecommendationForm = new Recommendationform($this->applicantForm);

        $form = $this->createForm('AppBundle\Form\RecommendationFormType', $RecommendationForm);
        $form->handleRequest($request);

        if ($form->isSubmitted() && $form->isValid()) {
            $em = $this->getDoctrine()->getManager();
            $em->persist($RecommendationForm);
            $em->flush();

            return $this->redirectToRoute('recommendationform_show', array('id' => $RecommendationForm->getId()));
        }

            return $this->render('recommendationform/new.html.twig', array(
                'RecommendationForm' => $RecommendationForm,
                'form' => $form->createView(),
            ));
    }

    /**
     * Finds and displays a RecommendationForm entity.
     *
     * @Route("/{id}", name="recommendationform_show")
     * @Method("GET")
     */
    public function showAction(RecommendationForm $RecommendationForm)
    {
        $deleteForm = $this->createDeleteForm($RecommendationForm);

        return $this->render('recommendationform/show.html.twig', array(
            'RecommendationForm' => $RecommendationForm,
            'delete_form' => $deleteForm->createView(),
        ));
    }

    /**
     * Displays a form to edit an existing RecommendationForm entity.
     *
     * @Route("/{id}/edit", name="recommendationform_edit")
     * @Method({"GET", "POST"})
     */
    public function editAction(Request $request, RecommendationForm $RecommendationForm)
    {
        $deleteForm = $this->createDeleteForm($RecommendationForm);
        $editForm = $this->createForm('AppBundle\Form\RecommendationFormType', $RecommendationForm);
        $editForm->handleRequest($request);

        if ($editForm->isSubmitted() && $editForm->isValid()) {
            $this->getDoctrine()->getManager()->flush();

            return $this->redirectToRoute('recommendationform_edit', array('id' => $RecommendationForm->getId()));
        }

        return $this->render('recommendationform/edit.html.twig', array(
            'RecommendationForm' => $RecommendationForm,
            'edit_form' => $editForm->createView(),
            'delete_form' => $deleteForm->createView(),
        ));
    }

    /**
     * Deletes a RecommendationForm entity.
     *
     * @Route("/{id}", name="recommendationform_delete")
     * @Method("DELETE")
     */
    public function deleteAction(Request $request, RecommendationForm $RecommendationForm)
    {
        $form = $this->createDeleteForm($RecommendationForm);
        $form->handleRequest($request);

        if ($form->isSubmitted() && $form->isValid()) {
            $em = $this->getDoctrine()->getManager();
            $em->remove($RecommendationForm);
            $em->flush();
        }

        return $this->redirectToRoute('recommendationform_index');
    }

    /**
     * Creates a form to delete a RecommendationForm entity.
     *
     * @param RecommendationForm $RecommendationForm The RecommendationForm entity
     *
     * @return \Symfony\Component\Form\Form The form
     */
    private function createDeleteForm(RecommendationForm $RecommendationForm)
    {
        return $this->createFormBuilder()
            ->setAction($this->generateUrl('recommendationform_delete', array('id' => $RecommendationForm->getId())))
            ->setMethod('DELETE')
            ->getForm()
        ;
    }
}

I have scoured all over the internet and just can't find an answer or figure out how it stopped working.

  • 写回答

1条回答 默认 最新

  • dongmacheng3222 2018-03-13 06:17
    关注

    I figured out what I changed and I'll put the answer here in case anyone wanted to do it. I was playing around with the different form methods and changed the form's original method from "GET" to POST (and all calls to the value in the controller were changed from "GET" to "POST"). On a whim, I changed it back and it's working again. I'm pretty sure I changed it because I didn't like that get methods put the query string in the address bar and mistakenly assumed that changing the method to post would fix it. If anyone has a recommendation of what to use instead of that, I welcome all suggestions.

    Not working controller:

    //...
    public function newAction(Request $request)
    {
        if(isset($_POST["accessCodeSS"])){
    
            $this->accessCode = $_POST["accessCodeSS"];
    //...
    }
    

    Correct working controller:

    public function newAction(Request $request)
    {
        if(isset($_GET["accessCodeSS"])){
    
            $this->accessCode = $_GET["accessCodeSS"];
    //...
    }
    

    Correct form (index.html.twig):

    <form action="{{ path('recommendation_form_new') }}" method="GET">
        <input type="email" name="email" placeholder="Email Address">
        <input type="password" name="accessCodeSS" placeholder="Access Code">
        <input type="submit" name="submit" value="Submit">
    </form>
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 mmocr的训练错误,结果全为0
  • ¥15 python的qt5界面
  • ¥15 无线电能传输系统MATLAB仿真问题
  • ¥50 如何用脚本实现输入法的热键设置
  • ¥20 我想使用一些网络协议或者部分协议也行,主要想实现类似于traceroute的一定步长内的路由拓扑功能
  • ¥30 深度学习,前后端连接
  • ¥15 孟德尔随机化结果不一致
  • ¥15 apm2.8飞控罗盘bad health,加速度计校准失败
  • ¥15 求解O-S方程的特征值问题给出边界层布拉休斯平行流的中性曲线
  • ¥15 谁有desed数据集呀