Немного справочной информации. У меня есть две сущности, которые имеют двунаправленную связь: по сути, в форме заявки может быть только одна форма рекомендации. Когда рекомендатель заполняет форму, я хотел бы, чтобы это происходило автоматически, и я хотел бы выбрать только соответствующую форму приложения (защитить данные других пользователей) на основе определенного кода, который они вводят на созданной мною настраиваемой странице формы. Я не уверен, как это произошло, но однажды я заставил его работать, но по неизвестной причине он остановился и добавляет «NULL» для идентификатора формы кандидата в форму рекомендации в моей базе данных. Я включу всю информацию, которую могу:
РекомендацияФорма 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);
}
//...
}
Рекомендация Контроллер:
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()
;
}
}
Я рыскал по всему Интернету и просто не могу найти ответа или понять, как это перестало работать.






Я выяснил, что я изменил, и поставлю здесь ответ на случай, если кто-то захочет это сделать. Я играл с различными методами формы и изменил исходный метод формы с «GET» на POST (и все вызовы значения в контроллере были изменены с «GET» на «POST»). По прихоти поменял обратно, и снова работает. Я почти уверен, что изменил его, потому что мне не нравилось, что методы get помещают строку запроса в адресную строку и ошибочно полагали, что изменение метода публикации исправит это. Если у кого-то есть рекомендация, что использовать вместо этого, я приветствую все предложения.
Не работает контроллер:
//...
public function newAction(Request $request)
{
if (isset($_POST["accessCodeSS"])){
$this->accessCode = $_POST["accessCodeSS"];
//...
}
Правильный рабочий контроллер:
public function newAction(Request $request)
{
if (isset($_GET["accessCodeSS"])){
$this->accessCode = $_GET["accessCodeSS"];
//...
}
Правильная форма (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>