symfony 3.4 вставка формы в базу данных error500 - PullRequest
0 голосов
/ 14 февраля 2020

У меня проблема с symfony 3.4 ... это должно быть довольно просто, но ... Дело в том, что когда я пытаюсь создать простую форму и вставить данные в mysql базу данных ПОСЛЕ ПОДПИСКИ, я получаю error500. Проект уже находится на LIVE-сервере, а не локально, поэтому я не могу автоматически сгенерировать маршрут для работы с composer, я написал его вручную. Форма отдает хорошо. Mysql поля - id-int (11) AI и title- varchar (255).

Класс моей формы:


use AppBundle\Entity\IndexAdvantage;
use Symfony\Component\Form\AbstractType;
use Symfony\Component\Form\Extension\Core\Type\TextType;
use Symfony\Component\Form\FormBuilderInterface;
use Symfony\Component\OptionsResolver\OptionsResolver;

class IndexAdvantageType extends AbstractType
{
    /**
     * {@inheritdoc}
     */
    public function buildForm(FormBuilderInterface $builder, array $options)
    {
        $builder
            ->add('title', TextType::class, ['label' => 'Title'])
        ;
    }

    /**
     * {@inheritdoc}
     */
    public function configureOptions(OptionsResolver $resolver)
    {
        $resolver->setDefaults(array(
            'data_class' => 'AppBundle\Entity\IndexAdvantage'
        ));
    }

    /**
     * {@inheritdoc}
     */
    public function getBlockPrefix()
    {
        return 'appbundle_index_advantage';
    }
}

My Entity : AppBundle \ Entity \ IndexAdvantage. php

namespace AppBundle\Entity;

use Doctrine\ORM\Mapping as ORM;
use Gedmo\Mapping\Annotation as Gedmo;

/**
 * @ORM\Table(name="index_advantage")
 * @ORM\Entity(repositoryClass="AppBundle\Repository\IndexAdvantageRepository")
 */
class IndexAdvantage
{
    /**
     * @ORM\Column(name="id", type="integer")
     * @ORM\Id
     * @ORM\GeneratedValue(strategy="AUTO")
     */
    private $id;

    /**
     * @ORM\Column(name="title", type="string", length=255)
     */
    private $title;

    /**
     * @return int|null
     */
    public function getId(): ?int
    {
        return $this->id;
    }

    /**
     * @return string
     */
    public function getTitle()
    {
        return $this->title;
    }

    /**
     * @param string $title
     * @return $this
     */
    public function setTitle($title)
    {
        $this->title = $title;
        return $this;
    }
}

Мой контроллер AppBundle \ Controller \ Admin \ IndexController. php

namespace AppBundle\Controller\Admin;

use AppBundle\Controller\AbstractBaseController;
use AppBundle\Form\IndexAdvantageType;
use AppBundle\Entity\IndexAdvantage;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\Routing\Annotation\Route;
use Doctrine\ORM\EntityManagerInterface;


class AdminIndexController extends AbstractBaseController
{
    /**
     * @Route("/admin/")
     */
    public function IndexAction()
    {
        return $this->render('AppBundle:AdminIndex:index.html.twig', array());
    }
...<<<<SOME OTHER FUNCTIONS>>>>>>>.....
    /**
     * @Route(
     *      "/advantage/new",
     *      name="admin.index_advantage.new",
     *      methods={"GET", "POST"}
     * )
     */
    public function newAdvantageAction(Request $request)
    {   
        $advantage = new IndexAdvantage();
        $form = $this->createForm('AppBundle\Form\IndexAdvantageType', $advantage);
        $form->handleRequest($request);

        if ($form->isSubmitted() && $form->isValid()) {

            $advantage = $form->getData();
            $em = $this->getDoctrine()->getManager();
            $em->persist($advantage);
            $em->flush($advantage);
        }

        return $this->render(
            'AppBundle:AdminIndexAdvantage:new.html.twig',['form' => $form->createView()]
        );
    }
}

Моя веточка формы AppBundle \ Resources \ view \ AdminIndexAdvantage \ new. html .twig

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

{% block content %}
    <h1>NEW</h1>
    {{ form_start(form) }}
        {{ form_widget(form) }}
        <input class="btn btn-success" type="submit" value="Create" />
    {{ form_end(form) }}
{% endblock %}

Я также создал маршрут вручную для работы newAdvantageAction при var/cache/prod/appProdProjectContainerUrlGenerator.php и var/cache/prod/appProdProjectContainerUrlMatcher.php

        'admin.index_advantage.new' => array (0 => array (0 => 'id',),
  1 => array ('_controller' =>'AppBundle\\Controller\\Admin\\AdminIndexController::newAdvantageAction',),
  2 => array (  ),
  3 => array (0 => array (0 => 'text', 1 => '/advantage/new',), 1 =>array (0 => 'variable', 1 => '/', 2 => '[^/]++', 3 => 'id',), 2 => array ( 0 => 'text', 1 => '/admin/index',),), 4 => array (  ), 5 => array (  ),),

и

                // admin_index_advantage_new
                if (0 === strpos($pathinfo, '/admin/index') && preg_match('#^/admin/index/(?P<id>[^/]++)/advantage/new$#sD', $pathinfo, $matches)) {
                    $ret = $this->mergeDefaults(array_replace($matches, ['_route' => 'admin.index_advantage.new']), array (  '_controller' => 'AppBundle\\Controller\\Admin\\AdminIndexController::newAdvantageAction',));
                    if (!in_array($canonicalMethod, ['GET', 'POST'])) {
                        $allow = array_merge($allow, ['GET', 'POST']);
                        goto not_adminindex_advantagenew;
                    }

                    return $ret;
                }
                not_adminindex_advantagenew:

1 Ответ

0 голосов
/ 22 февраля 2020

Я добавил маршрут admin_index_advantage_new:

#app/config/routng.yaml

app:
    resource: "@AppBundle/Controller/"
    type:     annotation

fos_user:
    resource: "@FOSUserBundle/Resources/config/routing/all.xml"

_liip_imagine:
    resource: "@LiipImagineBundle/Resources/config/routing.xml"

admin_index_advantage_new:
  path: /advantage/new
  defaults: { _controller: AppBundle:AdminIndexAdvantage:new }

он должен выполнить:

namespace AppBundle\Controller\Admin;

use AppBundle\Controller\AbstractBaseController;
use AppBundle\Entity\IndexAdvantage;
use AppBundle\Entity\Laboratory;
use AppBundle\Form\IndexAdvantageType;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\Routing\Annotation\Route;


class AdminIndexAdvantageController extends AbstractBaseController
{

    public function newAction()
    {
        return $this->render('AppBundle:AdminIndexAdvantage:new.html.twig');
    }

}

и go на domain.com/advantage/new, и я получаю '404 страница не найдена ': /

...