Giter Site home page Giter Site logo

unclead / yii2-multiple-input Goto Github PK

View Code? Open in Web Editor NEW
390.0 35.0 124.0 2.04 MB

Yii2 widget for handle multiple inputs for an attribute of model

Home Page: https://unclead.github.io/yii2-multiple-input/

License: BSD 3-Clause "New" or "Revised" License

PHP 43.10% CSS 0.95% JavaScript 55.95%
yii2 yii2-widgets

yii2-multiple-input's Introduction

Yii2 Multiple input widget.

Yii2 widget for handle multiple inputs for an attribute of model and tabular input for batch of models.

Latest Stable Version Total Downloads Daily Downloads Latest Unstable Version License

Latest release

The latest stable version of the extension is v2.27.0 Follow the instruction for upgrading from previous versions

Installation

The preferred way to install this extension is through composer.

Either run

php composer.phar require  unclead/yii2-multiple-input "~2.0"

or add

"unclead/yii2-multiple-input": "~2.0"

to the require section of your composer.json file.

Basic usage

Single column example

For example you want to have an ability of entering several emails of user on profile page. In this case you can use yii2-multiple-input widget like in the following code

use unclead\multipleinput\MultipleInput;

...

<?php
    echo $form->field($model, 'emails')->widget(MultipleInput::className(), [
        'max'               => 6,
        'min'               => 2, // should be at least 2 rows
        'allowEmptyList'    => false,
        'enableGuessTitle'  => true,
        'addButtonPosition' => MultipleInput::POS_HEADER, // show add button in the header
    ])
    ->label(false);
?>

Documentation

You can find a full version of documentation here

License

yii2-multiple-input is released under the BSD 3-Clause License. See the bundled LICENSE.md for details.

yii2-multiple-input's People

Contributors

antkaz avatar arogachev avatar bscheshirwork avatar cebe avatar dbd5 avatar digitv avatar dimmitri avatar execut avatar fiamma06 avatar hirenbhut93 avatar insaneskull avatar kirde avatar kongoon avatar nidgetgod avatar programmis avatar sankam-nikolya avatar spell6inder avatar thiagotalma avatar ua0leg avatar unclead avatar veksa avatar yus-ham avatar zayec77 avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

yii2-multiple-input's Issues

Ошибка при обновлении до 1.2.0

подключаю примерно так

field($model, 'subservices')->widget(\unclead\widgets\MultipleInput::className(), [ 'columns' => [ [ 'name' => 'name', 'title' => 'Доп.Услуга', 'type'=>'textInput', ], .... ]?>

имена полей раньше были что-то вроде Service[subservices][0][name], то теперь Service[0][name]. Толи бага толи фича..но у меня все сломала, откатился до 1.1.0 все норм

Баг checkBox

Снова привет, решил снова использовать твое расширение, в этот раз поле checkbox..

    'columns' => [
        [
            'name'  => 'enable_subdomain',
            'title' => 'Отображать в поддоменах?',
            'type'  => 'checkbox',
            'options'=>[
                'class'=>''
            ],
        ],
    ]

В общем проблема в том, что каждому input в строке 182 MultipleInputColumn проставляется класс form-control... что делает отображение checkbox очень странным) думаю с другими типами аналогично..лучше бы сделать так -> если class в options указан ставить его, если нет то ставить дефолтный form-control

bad pattern on regexp

In
unclead/widgets/renderers/TableRenderer.php, line 141
instead of:

$cells[0] = preg_replace('/^(<td[^>]+>)(.*)(<\/td>)$/', '${1}' . $hiddenInputs . '$2$3', $cells[0]);

we need this (with s (PCRE_DOTALL) modifier):

$cells[0] = preg_replace('/^(<td[^>]+>)(.*)(<\/td>)$/s', '${1}' . $hiddenInputs . '$2$3', $cells[0]);

for multiline search inside of 'td' tag.
Do you agree?

Remove previous plus/remove events

When I use AJAX to load a form with the multiple input element in a modal popup, the script attaches events to $(document) for the plus and minus buttons multiple times. When I click on the plus button after loading the form the second time, it adds two fields instead of just one.

Please remove the previous events.

--- jquery.multipleInput.js     2015-11-11 13:06:09.067983422 -0800
+++ jquery.multipleInput.js.new 2015-11-11 13:03:33.743983347 -0800
@@ -77,11 +77,13 @@
                 attributeDefaults: {}
             });

+            $(document).off('click.multipleInput', '#' + settings.id + ' .js-input-remove');
             $(document).on('click.multipleInput', '#' + settings.id + ' .js-input-remove', function (e) {
                 e.preventDefault();
                 methods.removeInput.apply(this);
             });

+            $(document).off('click.multipleInput', '#' + settings.id + ' .js-input-plus');
             $(document).on('click.multipleInput', '#' + settings.id + ' .js-input-plus', function (e) {
                 e.preventDefault();
                 methods.addInput.apply(this);

class is not working

why my option 'class' => 'form-control', is not being applied??

  echo \unclead\widgets\TabularInput::widget([
        'models' => $model->Tributos,
        'columns' => [
            [
                'type' => Form::INPUT_TEXT,
                'options' => ['readonly' => true, 'maxlength' => 45],
                'name' => 'Nombre',
                'title'=>'Nombre'
            ],
            [
                'name' => "BaseImponible",
                'title'=>'Base Imponible',
                'type' => \yii\widgets\MaskedInput::className(),
                'options' => [
                    'class' => 'form-control',
                    'mask' => '999-999-99-99'
                ]
            ]
        ],
    ]);
<td class="list-cell__BaseImponible"><div class="form-group field-comprobantetributo-4-baseimponible"><input type="text" id="comprobantetributo-4-baseimponible" name="ComprobanteTributo[4][BaseImponible]" data-plugin-inputmask="inputmask_892303c7"></div></td>

image

thanks!!

Improve documentation on validating

In docs/multiple_input_single.md there's an example of validating through separate function with foreach loop.
The same can be done with each validator that is available since yii 2.0.4:

[['email'], 'each', 'rule'=>['email']],

MultipleInput allowEmptyList

When using allowEmptyList there is one empty line for record addition.
I want that initially there were no lines, and appeared only when pressing the button to add.

Possibility to skip columns

When I use the MultipleInput for a single field (for example, a list of BCC email addresses), the input models are posted as MyForm[bcc][bcc][0]. Would it be possible to skip the columns and just post it as MyForm[bcc][0]? This way, you can use the default 'each' validator with an existing rule. At the moment, a custom validation method seems to be required.

Не прорисовывается последняя кнопка удаления

2016-02-19 19-02-13
Вот эта кнопка не прорисовывалась, пока я не изменил в TableRenderer строку 421
if ($index < $this->min || $index == $this->limit + 1) {
добавив +1 к лимиту.
Вот как я вызываю виджет:

      <?= TabularInput::widget([
                    'models' => (count($model->bookingPhones) == 0)? [new BookingPhones()]:$model->bookingPhones,
                    'limit'=>Yii::$app->params['limitBookingPhones'],
                    'min'               => 1, // should be at least 1 rows
                    'attributeOptions' => [
                        'enableAjaxValidation'      => true,
                        'enableClientValidation'    => false,
                        'validateOnChange'          => false,
                        'validateOnSubmit'          => true,
                        'validateOnBlur'            => false,
                    ],
                    'columns' => [
                        [
                            'name' => 'id',
                            'type' => \unclead\widgets\TabularColumn::TYPE_HIDDEN_INPUT
                        ],
                        [
                            'name'  => 'phone_number',
                            'type'  => \unclead\widgets\MultipleInputColumn::TYPE_TEXT_INPUT,
                            'enableError'=>true,
                        ],
                    ],
                ]) ?>

Saving multi input to related model

Hi @unclead !

I have Gallery model. And I have related to it Videos model.

I need to save Videos model from Gallery ActiveForm.

class Gallery extends ActiveRecord {

public $video;

<?= $form->field($model, 'video')->widget(MultipleInput::className(), [
    'limit' => 5
]) ?>
...

public function getVideos()
{
    return $this->hasMany(Videos::className(), ['ext_id' => 'id'])->where(['ext_type'=>'gallery']);
}
...

Video filelds to save are

$image_model = new Videos;
$image_model->url = $video;
$image_model->ext_type = 'youtube';
$image_model->ext_type = 'gallery';
$image_model->ext_id  = $this->id;
$image_model->save();

How should I save fields to Video model from Gallery model?
In action or maybe in beforeSave method?

Incorrect behavior is case when `min` is equal to `limit`

The widget renders incorrect output in case when min and limit are equal

    echo $form->field($model, 'emails')->widget(MultipleInput::className(), [
        'limit'             => 6,
        'allowEmptyList'    => false,
        'enableGuessTitle'  => true,
        'min'               => 6, 
        'addButtonPosition' => MultipleInput::POS_HEADER // show add button in the header
    ])
    ->label(false);

It must renders 6 rows, but the count of rows depends on quantity of models.
If we already have 3 emails the widget will render 3 rows, if we have 5 emails - 5 rows.

Add new row should not copy values of the most recent row

On create, it works fine. When you click "+" to add new row, it gives you all blank value even though you may fill in values for your first row.

On update, when you click "+" to add new row, the new row will get the value of the closest row.
update
create

The reason for that is I will have "id" field hidden on update, so when I update existing value, I check for "id" in the database and update new values (not going to delete all and re-create all because other table will use the "id" as foreign key)

{multiple-input} pattern change not enough

If I use the kartik\typeahead\TypeAhead widget with the MultipleInput widget,
the TypeAhead generates, for example, the next JS code:

var persons_title_{multiple_index}_data_1 = new Bloodhound({"datumTokenizer":Bloodhound.tokenizers.obj.whitespace('value'),"queryTokenizer":Bloodhound.tokenizers.whitespace,"remote":{"url":"/basic/web/persons/country-list?q=QUERY","wildcard":"QUERY"}});
kvInitTA('persons_title-{multiple-index}', typeahead_7864e59a, [{"display":"value","name":"persons_title_{multiple_index}_data_1","source":persons_title_{multiple_index}_data_1.ttAdapter()}]);

As you see here the id (ex. persons_title-{multiple-index}) is converted to variable name (persons_title_{multiple_index}_data_1), but is not changed the multiple_index to the new index in 'addInput' function.
What do you think about this?

Rename js events

I think we should rename events to more convinient style.
For example,

  • addNewRow -> afterAddRow
  • removeRow -> afterRemoveRow

Alse can be usefull have event beforeDeleteRow

MaskedInput multiple mask failed

[
                'name' => 'value',
                'title' => 'Phone',
                'type' => MaskedInput::className(),
                'options' => [
                    'class' => 'input-phone',
                    'mask' => [
                        '+7(999) 999-99-99',
                        '+7(9999) 999-99-99',
                        '+7(99999) 999-99-99',
                    ]
                ]
            ],

Ошибка гинерации префикса

Инициализирую виджет:

<?= $form->field($model, 'phone')->widget(MultipleInput::class) ?>

При этом префикс создается не корректно:

<input type="text" id="representation-phone-phone-1" class="form-control" name="Representation[phone][phone][1]" value="asdfasdf">

Если я правильно понимаю результат должен быть:

<input type="text" id="representation-phone-1" class="form-control" name="Representation[phone][1]" value="asdfasdf">

Проблема наблюдается только в случае, если указывать (либо не указывать) один столбец.
Если указывать несколько столбцов, то все отрабатывает отлично.

Ошибка возникает во всех версия...

Widget для input

Добрый день.
Спасибо за расширение.
Как можно использовать и можно ли вообще использовать widget для одиночного input'a.
Сделал так

<?=$form->field($model,'arrAcc')->widget(MultipleInput::className(),[
        'limit' => 10,
        'columns' =>[
            [
                'type' =>Select2::className(),
                'name' => 'acc',
                'options' => [
                    'pluginOptions' => [
                        'allowClear' => true,
                        'minimumInputLength' => 2,
                        'ajax' => [
                            'url' => \yii\helpers\Url::to(['/ajax-select']),
                            'dataType' => 'json',
                            'data' => new JsExpression('function(params) { return {q:params.term}; }')
                        ],
                        'escapeMarkup' => new JsExpression('function (markup) { return markup; }'),
                        'templateResult' => new JsExpression('function(cmp_id) { return cmp_id.text; }'),
                        'templateSelection' => new JsExpression('function (cmp_id) { return cmp_id.text; }'),
                    ],
                ]
            ]
        ]
    ])?>

в итоге в запросе пришел массив следующего вида

[arrAcc] => Array
                (
                    [acc] => Array
                        (
                            [0] => 17
                            [1] => 7
                        )

                )

Можно ли сделать так ,чтобы в запросе при ходил массив следующего вида:

  [arrAcc] => Array
                        (
                            [0] => 17
                            [1] => 7
                        )

Default value for checkbox

'defaultValue' => false

it not works for 'type' => 'checkbox'. All JS-created checkboxes always created as checked.

The ability to use custom template

I think it can be useful be able to set custom template for rendering items.
Currently, the widget uses the table template for rendering items

bad pattern on regexp

Hello
the test case:
Tabular Input with kartik-v/yii2-widget-fileinput:

<?= TabularInput::widget([
    'allowEmptyList' => true,
    'models' => $models,
    'attributeOptions' => [
        // ...
    ],
    'columns' => [
        // ...
        [
            'name'  => 'imageFile',
            'title' => 'imageFile',
            'type'  => FileInput::className(),
            'options' => [
                'options' => ['accept' => 'image/*'],
                'pluginEvents' => [
                    'filecleared' => 'function () {
                            console.log('File cleared!);
            }',
                ],
            ],
        ],
    ],
]) ?>

this code generates the next javascript:

jQuery('#item-{multiple-index}-imagefile').fileinput(fileinput_84f9f1b5);
jQuery('#item-{multiple-index}-imagefile').on('filecleared', function () {
    console.log('File cleared');
});

this js code isn't found by this 'if' in BaseRenderer.php:

if (preg_match('/^[^{]+{multiple-index}.*$/', $js) === 1) {

I recommend the m (PCRE_MULTILINE) regexp modifier:

if (preg_match('/^[^{]+{multiple-index}.*$/m', $js) === 1) {

This working for me.

Sincerely, E.

Incorrect display of buttons when using both 'min' and 'limit'

I have two emails, with limit = 2 and min = 1. When I render the form, there is no red X button next to the second input. When I set the limit to 3 there is no button next to 3rd input.

Generally it looks like the last input doesn't have it's button correctly generated - inspector shows an empty block.

Add rowOptions parameter

I am using the yii2-multiple-input extension
and I want define more than one class to row on tabularInput,

for example:
this class: multiple-input-list__item
I want change to: "multiple-input-list__item and phone-number" 2 classes for one row
and in another to: "multiple-input-list__item and address"

How may I add this ?

thanks man!

(sorry my bad english)

Отсутствует поле в POST запросе при пустом списке.

Никак не пойму.

Добавляю несколько записей, всё ок. удаляю одну, всё ок.
но если удаляю все записи, то при сохранении в POST запросе данное поле вообще нет, поэтому модель считает, что его сохранять ненадо, и в итоге последняя запись так и остается.

подскажите пожалуйста, где я накосячил?

MultipleInputColumn::TYPE_HIDDEN_INPUT does not render hidden input

sample code

 <?= 
        \unclead\widgets\TabularInput::widget([
            'models' => $claimingRules,
            'limit' => 5,
            'addButtonOptions' => [
                'class' => 'btn btn-success',
                'label' =>  Html::tag('i', null, ['class' => 'glyphicon glyphicon-plus']) // also you can use html code
            ],
            'attributeOptions' => [
                'enableAjaxValidation'      => false,
                'enableClientValidation'    => false,
                'validateOnChange'          => false,
                'validateOnSubmit'          => true,
                'validateOnBlur'            => false,
            ],
            'columns' => [
                [
                    'name' => 'id',
                    'title' => 'Hidden ID',
                    'type' => \unclead\widgets\MultipleInputColumn::TYPE_HIDDEN_INPUT
                ],
                [
                    'name'  => 'identifier',
                    'title' => 'Rule ID',
                    'enableError' => true
                ],
                [
                    'name'  => 'percent',
                    'title' => 'Claiming Rule Percent',
                    'enableError' => true
                ],
            ],
        ]) 
    ?>

Улучшение для связанных списков

Хотелось бы иметь возможность задавать что-то вроде

options=>[
    'items'=>function($data){
         return Object::myStaticFunctionGetItems($data->field);
    }
]

То есть иметь возможность задавать массив items через анонимную функцию как и value.
Очень облегчит жизнь при создании связанных списков.

DropdownList

A Как исполизовать? dropDownList ArrayHelper ?

Deleting of first item problem

I've got a problem with deleting of first element. U can just to move up add button to column header for solving this problem.
widget menu frontend index menu

urlencoded field token

yii2-elfinder extension is using urlencoded field token - %7Bmultiple-index%7D, which is not replaced in jsTemplate, and then doesn't work correctly.

As a temporary solution I changed line 149 of jquery.multipleInput.js from
jsTemplate = settings.jsTemplates[i].replaceAll('{multiple-index}', data.currentIndex);
to
jsTemplate = settings.jsTemplates[i] .replaceAll('{multiple-index}', data.currentIndex) .replaceAll('%7Bmultiple-index%7D', data.currentIndex);

jQuery issues

I've spent for couple hours trying to get extension work, but could not.

Firstly, you can't use data() like this:

            $wrapper.data('multipleInput', {
                settings: settings,
                currentIndex: 0,
                attributeDefaults: {}
            });

It just doesn't work. The explonation is here: http://stackoverflow.com/questions/6827810/unable-to-set-data-attribute-using-jquery-data-api

Next, where did you get such events?

      $(document).on('click.multipleInput', ....);

I was trying to fix it, but it was like a snowball, and all that I got was just a single text input without able to add fields.

Radio/checkbox lists doesn't work correctly

For radio or checkbox lists does ot work ajax validation because this types of input does not correctly processed on js side

        addAttribute: function () {
            var id = $(this).attr('id'),
                ele = $('#' + $(this).attr('id')),
                wrapper = ele.closest('.multiple-input').first(),
                form = ele.closest('form');

            // do not add attribute which are not the part of widget
            if (wrapper.length == 0) {
                return;
            }

attribute is skipped because system cannot determine wrapper for it.

dropDownList dont work

New data fine may be added, but if I have already saved the model, and open to edit in the list selected the wrong item..podozrevaju that the problem is in the model MultipleInputColumn примерно в этой строчке $input = Html::$type($name,null, $this->items, $options);

Getting the title based on the attribute model

Great solution, but the 'title' question isn't solved.
The '+' sign staying there alone, without title, I can't find the proper solution unless the one below.
Probably we need a new property to turn on/off the title and for BC.
(I think we need a title when 'allowEmptyList' is true...)

    protected function guessColumns()
    {
        if (empty($this->columns) && $this->hasModel()) {
            $this->columns = [
                [
                    'name' => $this->attribute,
                    'type' => MultipleInputColumn::TYPE_TEXT_INPUT,
                    'title' =>$this->model->getAttributeLabel($this->attribute), // recommended line
                ]
            ];
        }
    }

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.