sfWidgetFormSelect2Autocompleter::configure()   A
last analyzed

Complexity

Conditions 1
Paths 1

Size

Total Lines 23
Code Lines 19

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
c 1
b 0
f 0
dl 0
loc 23
rs 9.0856
cc 1
eloc 19
nc 1
nop 2
1
<?php
2
require_once(dirname(__FILE__) . '/../select2/Select2.class.php');
3
4
/**
5
 * This widget is designed to generate more user friendly autocomplete widgets.
6
 *
7
 * @package     symfony
8
 * @subpackage  widget
9
 * @link        https://github.com/19Gerhard85/sfSelect2WidgetsPlugin
10
 * @author      Ing. Gerhard Schranz <[email protected]>
11
 * @version     0.1 2013-03-11
12
 */
13
class sfWidgetFormSelect2Autocompleter extends sfWidgetFormInput
14
{
15
    /**
16
     * Configures the current widget.
17
     *
18
     * Available options:
19
     *
20
     *  * url:            The URL to call to get the choices to use (required)
21
     *  * config:         A JavaScript array that configures the JQuery autocompleter widget
22
     *  * value_callback: A callback that converts the value before it is displayed
23
     *
24
     * @param array $options     An array of options
25
     * @param array $attributes  An array of default HTML attributes
26
     *
27
     * @see sfWidgetForm
28
     */
29
    protected function configure($options = array(), $attributes = array())
30
    {
31
        $this->addRequiredOption('url');
32
        $this->addRequiredOption('model');
33
        $this->addOption('value_callback', array($this, 'toString'));
34
        $this->addOption('method', '__toString');
35
36
        $this->addOption('culture', sfContext::getInstance()->getUser()->getCulture());
37
        $this->addOption('width', sfConfig::get('sf_sfSelect2Widgets_width'));
38
        $this->addOption('minimumInputLength', 2);
39
        $this->addOption('placeholder', '');
40
        $this->addOption('allowClear', true);
41
        $this->addOption('formatSelection', 'defaultFormatResult');
42
        $this->addOption('formatResult', 'defaultFormatResult');
43
        $this->addOption('formatNoMatches', 'defaultFormatNoMatches');
44
        $this->addOption('formatInputTooShort', 'defaultFormatInputTooShort');
45
        $this->addOption('containerCss', '');
46
        $this->addOption('containerCssClass', '');
47
        $this->addOption('dropdownCss', '');
48
        $this->addOption('dropdownCssClass', '');
49
50
        parent::configure($options, $attributes);
51
    }
52
53
    public function getChoices()
54
    {
55
        $choices = parent::getChoices();
56
57
        if (count($choices) > 0 && isset($choices['']) && $choices[''] == '') {
58
            $choices[''] = '&nbsp;';
59
        }
60
61
        return $choices;
62
    }
63
64
    /**
65
     * @param  string $name        The element name
66
     * @param  string $value       The date displayed in this widget
67
     * @param  array  $attributes  An array of HTML attributes to be merged with the default HTML attributes
68
     * @param  array  $errors      An array of errors for the field
69
     *
70
     * @return string An HTML tag string
71
     *
72
     * @see sfWidgetForm
73
     */
74
    public function render($name, $value = null, $attributes = array(), $errors = array())
75
    {
76
        $visible_value = escape_javascript($this->getOption('value_callback') ? call_user_func($this->getOption('value_callback'), $value) : $value);
77
78
        sfContext::getInstance()->getConfiguration()->loadHelpers('Url');
79
80
        $id = $this->generateId($name);
81
82
        $return = $this->renderTag('input', array(
83
            'type'  => 'hidden',
84
            'name'  => $name,
85
            'value' => $value
86
        ));
87
88
        $return .= sprintf(<<<EOF
89
<script type="text/javascript">
90
function defaultFormatResult(item)
91
{
92
    return item.text;
93
}
94
95
function defaultFormatNoMatches(term)
96
{
97
    return 'Keine Ergebnisse gefunden.';
98
}
99
100
function defaultFormatInputTooShort(term, minLength)
101
{
102
    return 'Bitte geben Sie mind. ' + minLength + ' Zeichen ein.';
103
}
104
105
jQuery("#%s").select2(
106
{
107
    width:                  '%s',
108
    minimumInputLength:     %s,
109
    placeholder:            '%s',
110
    allowClear:             %s,
111
    formatSelection:        %s,
112
    formatResult:           %s,
113
    formatNoMatches:        %s,
114
    formatInputTooShort:    %s,
115
    containerCss:           '%s',
116
    containerCssClass:      '%s',
117
    dropdownCss:            '%s',
118
    dropdownCssClass:       '%s',
119
    ajax: {
120
        url:        '%s',
121
        dataType:   'json',
122
        quietMillis: 100,
123
        data:       function (term, page)
124
        {
125
            return {
126
                q:     term,
127
                limit: 10,
128
                page:  page
129
            };
130
        },
131
        results: function (data, page)
132
        {
133
            var more = (page * 10) < data.total;
134
135
            return {results: data.items, more: more};
136
        }
137
    }
138
});
139
140
jQuery('#%s').select2('data', { id: '%s', text: '%s' });
141
</script>
142
EOF
143
            ,
144
            $id,
145
            $this->getOption('width'),
146
            $this->getOption('minimumInputLength'),
147
            $this->getOption('placeholder', ''),
148
            $this->getOption('allowClear') == true ? 'true' : 'false',
149
            $this->getOption('formatSelection'),
150
            $this->getOption('formatResult'),
151
            $this->getOption('formatNoMatches'),
152
            $this->getOption('formatInputTooShort'),
153
            $this->getOption('containerCss'),
154
            $this->getOption('containerCssClass'),
155
            $this->getOption('dropdownCss'),
156
            $this->getOption('dropdownCssClass'),
157
            url_for($this->getOption('url')),
158
            $id,
159
            $value,
160
            $visible_value ? $visible_value : $this->getOption('placeholder', '')
161
        );
162
163
        return $return;
164
    }
165
166
    /**
167
     * Gets the stylesheet paths associated with the widget.
168
     *
169
     * @return array An array of stylesheet paths
170
     */
171
    public function getStylesheets()
172
    {
173
        return Select2::addStylesheets();
174
    }
175
176
    /**
177
     * Gets the JavaScript paths associated with the widget.
178
     *
179
     * @return array An array of JavaScript paths
180
     */
181
    public function getJavascripts()
182
    {
183
        return Select2::addJavascripts($this->getOption('culture'));
184
    }
185
186
    protected function toString($value)
187
    {
188
        $class = constant($this->getOption('model').'::PEER');
189
190
        if ($class::hasBehavior('soft_delete'))
191
        {
192
            $class::disableSoftDelete();
193
        }
194
195
        $object = call_user_func(array($class, 'retrieveByPK'), $value);
196
197
        if ($class::hasBehavior('soft_delete'))
198
        {
199
            $class::enableSoftDelete();
200
        }
201
202
        $method = $this->getOption('method');
203
204 View Code Duplication
        if (!method_exists($this->getOption('model'), $method))
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated across your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
205
        {
206
            throw new RuntimeException(sprintf('Class "%s" must implement a "%s" method to be rendered in a "%s" widget', $this->getOption('model'), $method, __CLASS__));
207
        }
208
209
        return !is_null($object) ? $object->$method() : '';
210
    }
211
}
212