简体   繁体   中英

Adding and Edit form fields to database Symfony 2

I need a help in solving my problem with Symfony2. I am quite new in it. I have a twig file with form in which I add test name and its category's names, on each category field I set name and the color for the category. When I gave add to my form it adds only test Name in the database instead of adding all parameters. I can't understand where I have made mistake in adding categories and it's field color to database and how to create an EDIT form, to edit my test's categories for the current Test....

my default controller:

 public function newAction( $options = 0 )
   {
    $em = $this->getDoctrine()->getManager();
    $tests =  $em->getRepository('LadelaOdeskTesterBundle:Test')->findAll();

    return compact( 'tests', 'options' );
}

/**
 * @Route("/add/test", requirements={"name" = "\s+"}, name="test.create")
 * @Method("Post")
 * @return array
 */
public function createAction()
{
    $success = 0;
    $name = $this->getRequest()->get('name');
    $category = $this->getRequest()->get('category-new');

    if( !empty($name) )
    {
        $test = new Test();
        $test->setName($this->getRequest()->get('name'));

        $em = $this->getDoctrine()->getManager();
        $em->persist($test);
        $em->flush();

        $success = 'Test '.$test->getName().' was created';
    }
    else
    {
        $success = 'Test name can not be empty';
    }

    if( !empty($category) )
    {
        $categoryName = new Category();
        $categoryName->setName($this->getRequest()->get('name'));
        $categoryName->setColor($this->getRequest()->get('color'));

        $em = $this->getDoctrine()->getManager();
        $em->persist($categoryName);
        $em->flush();

        $success = 'Category '.$categoryName->getName().' was created';
    }
    else
    {
        $success = 'Category name can not be empty';
    }
    return $this->redirect($this->generateUrl('test.new'));
}

/**
 * @Route("/edit/test", requirements={"category" = "\s+"}, name="edit.test")
 * @Method("GET")
 * @return array
 */   
public function editAction()
{
     $success = 0;
     $category = $this->getRequest()->get('category-new');

    if( !empty($category) )
    {
        $test = new Test();
        $test->setName($this->getRequest()->get('category'));

        $em = $this->getDoctrine()->getManager();
        $em->persist($test);
        $em->flush();

        $success = 'Category '.$test->getName().' was edited';
    }
    else
    {
        $success = 'Category name can not be empty';
    }

    return $this->redirect($this->generateUrl('category.new'));
    }
 }

my Category Entity:

class Category
 {
/**
 * @var integer $id
 *
 * @ORM\Column(name="id", type="integer")
 * @ORM\Id
 * @ORM\GeneratedValue(strategy="AUTO")
 */
private $id;

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

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

public function __construct()
{
    $this->color = '255,255,0'; // default color for category
}

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

/**
 * Set name
 *
 * @param string $name
 * @return Category
 */
public function setName($name)
{
    $this->name = $name;

    return $this;
}

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

/**
 * Set color
 *
 * @param string $color
 * @return Category
 */
public function setColor($color)
{
    $this->color = $color;

    return $this;
}

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

}

my test Entity:

 class Test
  {
/**
 * @var integer $id
 *
 * @ORM\Column(name="id", type="integer")
 * @ORM\Id
 * @ORM\GeneratedValue(strategy="AUTO")
 */
private $id;

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

/**
 * @var \DateTime $created_at
 *
 * @Gedmo\Timestampable(on="create")
 * @ORM\Column(name="created_at", type="datetime")
 */
private $created_at;

/**
 * @Gedmo\Slug(fields={"name"})
 * @ORM\Column(length=128,unique=true)
 */
private $slug;

/**
 * @ORM\ManyToMany(targetEntity="Question")
 * @ORM\JoinTable(name="test_questions",
 *      joinColumns={@ORM\JoinColumn(name="test_id", referencedColumnName="id")},
 *      inverseJoinColumns={@ORM\JoinColumn(name="question_id",    referencedColumnName="id")}
 *      )
 * @var Collection $questions
 **/
protected $questions;

/**
 * @ORM\ManyToMany(targetEntity="Result")
 * @ORM\JoinTable(name="test_results",
 *      joinColumns={@ORM\JoinColumn(name="test_id", referencedColumnName="id")},
 *      inverseJoinColumns={@ORM\JoinColumn(name="result_id", referencedColumnName="id")}
 *      )
 * @var Collection $results
 **/
protected $results;

 /**
   * @ORM\ManyToMany(targetEntity="Category")
   * @ORM\JoinTable(name="test_categories",
    *      joinColumns={@ORM\JoinColumn(name="test_id", referencedColumnName="id")},
    *      inverseJoinColumns={@ORM\JoinColumn(name="category_id", 
    *      )
    * @var Collection $categories
    **/
 protected $categories;

/**
 * @var \DateTime $updated_at
 *
 * @Gedmo\Timestampable(on="update")
 * @ORM\Column(name="updated_at", type="datetime")
 */
private $updated_at;

public function __construct()
{
    $this->questions = new \Doctrine\Common\Collections\ArrayCollection();
    $this->categories = new \Doctrine\Common\Collections\ArrayCollection();
}

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

/**
 * Set name
 *
 * @param string $name
 * @return Test
 */
public function setName($name)
{
    $this->name = $name;

    return $this;
}

public function getSlug()
{
    return $this->slug;
}

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

/**
 * Set created_at
 *
 * @param \DateTime $createdAt
 * @return Test
 */
public function setCreatedAt($createdAt)
{
    $this->created_at = $createdAt;

    return $this;
}

/**
 * Get created_at
 *
 * @return \DateTime
 */
public function getCreatedAt()
{
    return $this->created_at;
}

/**
 * Set updated_at
 *
 * @param \DateTime $updatedAt
 * @return Test
 */
public function setUpdatedAt($updatedAt)
{
    $this->updated_at = $updatedAt;

    return $this;
}

/**
 * Get updated_at
 *
 * @return \DateTime
 */
public function getUpdatedAt()
{
    return $this->updated_at;
}

/**
 *
 */
public  function getQuestions()
{
    return $this->questions;
}

public function addQuestion( Question $question )
{
    $this->questions[] = $question;
}

/**
 * Set slug
 *
 * @param string $slug
 * @return Test
 */
public function setSlug($slug)
{
    $this->slug = $slug;

    return $this;
}

/**
 * Remove questions
 *
 * @param Question $questions
 */
public function removeQuestion( Question $questions)
{
    $this->questions->removeElement($questions);
}

/**
 * Add results
 *
 * @param Result $results
 * @return Test
 */
public function addResult(Result $results)
{
    $this->results[] = $results;

    return $this;
}

/**
 * Remove results
 *
 * @param Result $results
 */
public function removeResult(Result $results)
{
    $this->results->removeElement($results);
}

/**
 * Get results
 *
 * @return Collection
 */
public function getResults()
{
    return $this->results;
}

public function countResults()
{
    return $this->results->count();
}

public function countQuestions()
{
    return $this->questions->count();
}


/**
 * Add categories
 *
 * @param Ladela\OdeskTesterBundle\Entity\Category $categories
 * @return Test
 */
public function addCategorie(\Ladela\OdeskTesterBundle\Entity\Category $categories)
{
    $this->categories[] = $categories;

    return $this;
}

/**
 * Remove categories
 *
 * @param Ladela\OdeskTesterBundle\Entity\Category $categories
 */
public function removeCategorie(\Ladela\OdeskTesterBundle\Entity\Category $categories)
{
    $this->categories->removeElement($categories);
}

/**
 * Get categories
 *
 * @return Doctrine\Common\Collections\Collection 
 */
public function getCategories()
{
    return $this->categories;
}
 }

my twig file:

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

  {% block stylesheets %}
 {{ parent() }}
  <link rel="stylesheet" href="{{ asset('bundles/ladelaodesktester/css/new.css') }}"   
<link rel="stylesheet" href="{{ asset('bundles/ladelaodesktester/css/colorpicker.css') 
<link rel="stylesheet" href="{{ asset('bundles/ladelaodesktester/css/layout.css') }}" 
 {% endblock %}

  {% block body %}
 <ul id="breadcrumb">
<li><a href="{{path('homepage')}}" title="Home"><img src="{{  
asset('bundles/ladelaodesktester/images/home.png') }}" alt="Home" class="home" /></a>
</li>
<li><a href="{{path('test.new')}}" title="New"> New test </a></li>
<li> Please add data to new test </li>
 </ul>
 {#<div class="wrap">#}
 <div class="new-test">
  <h2>New test </h2>
   <form action="{{ path('test.create') }}" method="post">
        Test name: <input type="text" name="name-new"/><br>
        Category 1  <input class="color {valueElement:'myValue'}" type="text"
        name="category-new"><br>
        Category 2  <input class="color {valueElement:'myValue1'}" type="text"
        name="category-new"><br>
        Category 3  <input class="color {valueElement:'myValue2'}" type="text"
        name="category-new"><br>
        Category 4  <input class="color {valueElement:'myValue3'}" type="text" 
        name="category-new"><br>
        Category 5  <input class="color {valueElement:'myValue4'}" type="text"
        name="category-new"><br>
        Category 6  <input class="color {valueElement:'myValue5'}" type="text"
        name="category-new"><br>
        Category 7  <input class="color {valueElement:'myValue6'}" type="text" 
        name="category-new"><br>
        Category 8  <input class="color {valueElement:'myValue7'}" type="text"
         name="category-new"><br>

        Category 9  <input class="color {valueElement:'myValue8'}" type="text"
        name="category-new"><br>
        Category 10  <input class="color {valueElement:'myValue9'}" type="text" 
        name="category-new"><br>
        <input type="submit" value="Add">
     </form>
   </div>
 <table class="test-list">
<caption></caption>
<tbody>
    <tr>
        <th>Test name</th>
        <th># questions</th>
        <th># passed</th>
        <th># action</th>
    </tr>
    {% for test in tests %}
    <tr>
        <td>
           {{ test.name }}
        </td>
        <td>
           {{ test.countquestions }}
        </td>
        <td>
            {{ test.countresults }}
        </td>
        <td>
            <a href="{{ path('test.show', { 'slug': test.slug }) }}">analyze</a>|
            <a href="">new result</a> |
            <a href="{{ path('edit.test') }}">edit </a>
        </td>
      </tr>
      {% endfor %}
  </tbody>
 </table>
  {#</div>#}
  {% endblock %}
 {% block javascripts %}
{{ parent() }}
<script src="{{ asset('bundles/ladelaodesktester/js/new.js') }}" 
type="text/javascript"></script>
<script src="{{ asset('bundles/ladelaodesktester/js/jscolor.js') }}"
 type="text/javascript"></script>
 {% endblock %}

Your category inputs have no value attribute in markup so unless user populates them they won't submit properly. Since they also all have the same name should add [] to name so they submit as array

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM