dsf22567
dsf22567
2015-09-06 08:52

Symfony textfield ajax用户

I have a Message entity and a User one. I want to make users be able to send messages to others. I already can send and receive messages, everything is working fine, but in order to select the receiver of a message, a default drop-down with all the users is made.

What I want to do is change the drop-down to a text field and make an AJAX to the database and retrieve a list of users that are found matching the keyword inserted in the textfield. And when clicking upon one of them, the user is introduced in the textfield.

The problem that I am facing is that I don't know how to pass an entity instead of plaintext because I get this error

Argument 1 passed to PrivateMessageBundle\Entity\Message::setReceiver() must be an instance of CrudBundle\Entity\User, string given

Another question, is there a bundle or plugin that does this easier and I can modify? Or do I have to do it myself everytime for every ajax field?

I'm building the form like so

$builder
    ->add('title')
    ->add('content','textarea')
    ->add('receiver','text');

By default, receiver is a drop-down select and automatically selects the User entity, but once I change it to text it doesn't.

Here's also relevant parts of my entities, if you need them:

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

    /**
     * @var string
     *
     * @ORM\Column(name="title", type="string", length=50)
     */
    protected $title;

    /**
     * @ORM\ManyToOne(targetEntity="CrudBundle\Entity\User")
     * @ORM\JoinColumn(referencedColumnName="id")
     */
    protected $receiver;
    /**
     * @ORM\ManyToOne(targetEntity="CrudBundle\Entity\User")
     * @ORM\JoinColumn(referencedColumnName="id")
     */
    protected $sender;

    /**
     * @var string
     *
     * @ORM\Column(name="content", type="string", length=2000)
     */
    protected $content;

And my User class, extending FOSUserBundle's BaseUser class.

class User extends BaseUser implements AuthorInterface
{
    /**
     * @ORM\Id
     * @ORM\Column(type="integer")
     * @ORM\GeneratedValue(strategy="AUTO")
     */
    protected $id;
  • 点赞
  • 写回答
  • 关注问题
  • 收藏
  • 复制链接分享
  • 邀请回答

1条回答

  • doushanlv5184 doushanlv5184 6年前

    I think there are two ways to solve this problem.

    1) add a custum formfield with the mapped = FALSE attribute.

    ->add('ajaxsearch', null, array('mapped' => false))
    

    2) use a data-transformer.

    点赞 评论 复制链接分享