Symfony/bootstrap中是否可能有一个自动完成文本框? [英] Is it possible to have an autocomplete text box in Symfony/bootstrap?

查看:95
本文介绍了Symfony/bootstrap中是否可能有一个自动完成文本框?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我将Symfony 2.4与Braincrafted Bootstrap捆绑包一起使用.我一直在寻找一种在Bootstrap中具有自动填充文本框的方法,但看来我需要一个外部库来执行此操作("Typeahead"?).

I'm using Symfony 2.4 with the Braincrafted Bootstrap bundle. I have been searching for a way to have an autocompleting text box in Bootstrap but it appears I need an external library to do this ("Typeahead"?).

首先,使用Bootstrap绝对不可能做到这一点吗? 其次,除了Typeahead之外,还有其他推荐的替代方法吗?

Firstly, is it definitely not possible to do this natively with Bootstrap? And secondly, are there any recommended alternatives besides Typeahead?

谢谢

推荐答案

使用Symfony2可以完成 typeahead ,尽管这可能需要一些时间.这是一个分步示例:

A typeahead can be done with Symfony2 although it might take some time. Here is a step-by-step example:

由于Symfony2中的所有(或至少大多数)形式都已映射到实体,因此应从此处开始.您想要 typeahead 的实体的重要组成部分是__toString方法.在此示例中,我们有一个Address实体:

Since all (or at least most) forms in Symfony2 are mapped to entities you should start here. One important part of the entity you want a typeahead for is the __toString method. In this example we have an Address entity:

class Address
{
    /**
     * @ORM\Column(type="string")
     * @Assert\NotBlank(message="Please enter an address")
     */
    protected $addressstring;

    public function __toString()
    {
        return $this->getAddressstring();
    }        
}

表格:

现在,我们有了漂亮的小Address,可以将其添加到EventType表单中.在buildForm方法中,我们添加 address字段:

The form:

Now that we have our nice little Address lets add it to the EventType form. In the buildForm method we add our address field:

$builder->add(
    $builder->create(
        'address', 
        'text',
        ['attr' => ['class' => 'address_typeahead']]
    )
);

请注意,字段类型为文本,而不是实体.这给了我们文本输入而不是愚蠢的下拉菜单或复选框的优势.另外,我们添加了class属性以快速在javascript中获取该字段.

Notice that the field type is text and not entity. This gives us the advantage of a text-input instead of a stupid dropdown or checkbox thingy. Also we add a class attribute to get the field quickly in javascript.

让我们创建一个简单的表单模板:

Let's create a simple form template:

<form action="{{ path('event_add') }}" method="post" {{ form_enctype(form) }}>
    {{ form_widget(form) }}
    <input class="btn btn-primary" type="submit" value="Create Event" />
</form>

并在下面添加一些javascript:

$('.address_typeahead').typeahead({
    source: function (query, process) {
        var addressobj = $(this).parent();
        return $.get('{{ path('events_address_typeahead') }}', { 'addr': query }, function (data) {
            return process(data);
        });
    }
});

动作:

我们快到了.但是typeaheadAction丢失了.让我们将其添加到我们选择的控制器中:

The action:

We are almost there. But the typeaheadAction is missing. Let's add it to our controller of choice:

/**
 * @Route("/address/typeahead", name="events_address_typeahead")
 * @Method("GET")
 */
public function addressTypeaheadAction(Request $request)
{
    $addresses = // get all addresses e.g. from a repository

    return new JsonResponse(
        array_map(
            function ($val) {
                return (string) $val;
            },
            $addresses
        )
    );
}

打字提前现在应该已经在您的表单中为您提供了一些不错的选择.

Typeahead should now already present you with some nice options in your form.

我们在这里要做的最后一件事是添加DataTransformer.有了这个Symfony2,就可以将表单字段的值转换为另一种类型(或者在我们的情况下为实体).因此,让我们快速创建一个AddressTransformer:

The last thing we need to do here is to add a DataTransformer. With this Symfony2 is able to transform the value of a form field into another type (or in our case into an entity). So lets quickly create an AddressTransformer:

class StringToAddressTransformer implements DataTransformerInterface
{   
    /**
     * transforms the Address-Object into a String
     */
    public function transform($addrobj)
    {
        if (!$addrobj) {
            return null;
        }

        return $addrobj->__toString();
    }

    /**
     * Reverts Transformation from String to Address Object
     */
    public function reverseTransform($address)
    {

        if (null === $address) {
            return null;
        }

        // .. do anything to transform the string into an object

        return $addrobj;
    }
}

这台变形金刚真的在为我们做魔术!最后一步是将其添加到我们的表单中.从步骤2更改您的buildForm方法,如下所示:

This transformer is really doing the magic for us! The final step is to add it to our form. Change your buildForm method from step 2 as follows:

$builder->add(
    $builder->create(
        'address', 
        'text',
        ['attr' => ['class' => 'address_typeahead']]
    )->addModelTransformer(new StringToAddressTransformer())
);

Aaaaa,您完成了!

Aaaaaand you are done!

  • Doc about DataTransformer
  • Older project of me where this example is from

这篇关于Symfony/bootstrap中是否可能有一个自动完成文本框?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆