Giter Club home page Giter Club logo

forms-multiplier's Introduction

Website 🚀 contributte.org | Contact 👨🏻‍💻 f3l1x.io | Twitter 🐦 @contributte

Usage

To install latest version of contributte/forms-multiplier use Composer.

composer require contributte/forms-multiplier

Documentation

For details on how to use this package, check out our documentation.

Versions

State Version Branch PHP
dev ^4.1 master >=8.0
stable ^4.0 master >=8.0

Development

See how to contribute to this package. This package is currently maintained by these authors.


Consider to support contributte development team. Also thank you for using this package.

forms-multiplier's People

Contributors

adaamz avatar attanon avatar bigohenry avatar dg avatar diegosardina avatar f3l1x avatar jakubvojacek avatar jankonas avatar jtojnar avatar kocicak avatar krajicj avatar mabar avatar martenb avatar martkcz avatar mikkuba avatar mistrfilda avatar petrparolek avatar thoronir42 avatar vody105 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

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

forms-multiplier's Issues

Nefunguje s verzí latte 2.5.1

Při update latte 2.4.8->2.5.1 hazí chybu

Argument 1 passed to Latte\PhpWriter::formatWord() must be of the type string, integer given, called in /home/pavlenda/web/nakatamaranu.cz/public_html/vendor/latte/latte/src/Latte/Compiler/PhpWriter.php on line 83

S verzí 2.4.8 je to OK. M.

Grouping form submit with multiplier buttons

Hi,
i have whole form submit button after multiplier buttons and form renders them all (buttons) together in one group instead separetly, is there any workaround besides manual form render?

I have tried to use form groups, but that messed up multipliers adding new fields order. Which probably second issue ; )

Manual rendering example

Can you please add manual rendering example? I can't get remove button to work. I got this error: Component with name 'multiplier_remover' does not exist.

Form code:

$multiplier = $form->addMultiplier('metadata', [$this, 'addMetadata'], 0);
$multiplier->addCreateSubmit('Přidat');
$multiplier->addRemoveSubmit('Odebrat');

My template:

<table class="table table-bordered">
    <thead>
        <tr>
            <th>Název</th>
            <th>Hodnota</th>
            <th></th>
        </tr>
    </thead>
    <tbody>
        <tr n:foreach="$form['metadata']->getContainers() as $id => $container">
            <td n:foreach="$container->components as $name => $component" n:class="$component->name === 'vps_metadata_id' ? hide">
                {input metadata-$id-$name class => 'form-control'}
                <span class="help-block" style="color:#a94442" n:foreach="$component->errors as $error">{$error}</span>
            </td>
        </tr>
    </tbody>
    <tfoot>
        <tr>
            <td colspan="3" class="text-right">
                {input $form['metadata']['multiplier_remover'] class => 'btn btn-primary'}
                {input $form['metadata']['multiplier_creator'] class => 'btn btn-primary'}
            </td>
        </tr>
    </tfoot>
</table>

3.0.1 performing onSuccess event

Hello,

after the latest update (3.0.1) create button started performing onSuccess event on form, which makes it unusable. Do you have any idea how to solve it, or where the problem is?

Thank you for answer (and for this great plugin).

How to iterate containers after default values?

Hello, i have one problem. I need to iterate each control of Multiplier and set to label some attributes unique for each input:

foreach ($groups->getContainers() as $container) {
                        foreach ($container->getControls() as $control_name => $control) {
                            // some more logic here
                            $control->getLabelPrototype()->setAttribute('data-html', 'true');
                            $control->getLabelPrototype()->setAttribute('data-toggle', 'tooltip');
                            $control->getLabelPrototype()->setAttribute('data-placement', 'top');
                            $control->getLabelPrototype()->setAttribute('data-delay', '{"show":"1000", "hide":"0"}');
                            $control->getLabelPrototype()->setAttribute('title', $attribute_object->getAttributeInfo()->getFullInfoString());
                        }
                    }

The problem is, after this code Multiplier is broken. It display right, but if i made some changes in form values after form is send, there are no changes at values... The thing what break the Multiplier is this:

foreach ($groups->getContainers() as $container) {
                 
}

Yes, after i set the default values to Multiplier, this empty foreach break the Multiplier.

Any idea how correctly get to label prototyte to set some attributes?
Thank you very much

Why is method Container::setValues overwriten by Multiplier?

Is there any reason to overwrite method Nette\Forms\Container::setValues() in Multiplier? Becouse i can't find any.

With Multiplier::setValues() i can't use Form::setDefaults(). But when i commented out this method it works perfectly.

Is there any use case when you have to use Multiplier::setControlValues()?

post data not available

Hi,
I have current (9afdae2) version and have problem with accessing form data. When I dump($_REQUEST) I see everything was submitted via request. Hovever if I want to access multipliers items via $form->getValues()->multiplier there is no data. My multiplier has name variants:

$_REQUEST:
variants => 0 => rarity => "1" value => "500" text => "text"

$form->getValues():
variants => Nette\Utils\ArrayHash #1462

$form->getComponent("variants")->getComponents():
Nette\ComponentModel\RecursiveComponentIterator #ca3d

Did I miss something in documentation, badly register it or just simply replicator is not compatible with nette/3.0?

Is supported multiplier inside another multiplier? Or how to use it?

$tasks = $form->addMultiplier('tasks', function (Container $task) use ($redrawControl) {
	$task->addText('description', 'task_description')->setRequired('required_field');

	
	$options = $task->addMultiplier('options', function (Container $option) use ($redrawControl) {
			$option->addText('text', 'task_option_text')->setRequired('required_field');
	}, 2, 100);
	$options->addCreateButton('add_task_option', 1, $redrawControl);
	$options->addRemoveButton('remove', $redrawControl);
}, 0);
$tasks->addCreateButton('add_task', 1, $redrawControl);
$tasks->addRemoveButton('remove');

When i use sandbox form template, it generates only task container (description, add, remove). Options are not rendered. `

	<form n:name=$form class=form-horizontal>
	<ul class=error n:if="$form->ownErrors">
		<li n:foreach="$form->ownErrors as $error">{$error}</li>
	</ul>

	<div n:foreach="$form->controls as $name => $input"
		n:if="!$input->getOption(rendered) && $input->getOption(type) !== hidden"
		n:class="form-group, $input->required ? required, $input->error ? has-error">

		{label $input}

		{if $input->getOption(type) in [text, select, textarea]}
			{input $input class => form-control}
		{elseif $input->getOption(type) === button}
			<div class="text-center controls">{input $input class => "button primary"}</div>
		{elseif $input->getOption(type) === checkbox}
			<div class="checkbox">{input $input}</div>
		{elseif $input->getOption(type) === radio}
			<div class="radio">{input $input}</div>
		{else}
			{input $input}
		{/if}

		<span class=help-block n:ifcontent>{$input->error ?: $input->getOption(description)}</span>

	</div>
	</form>

Second effect is on remove task - Nette throws an exception

Nette\InvalidStateException
Component 'options' is not attached to 'Nette\Forms\Form'

MultiplierExtension not found

Hi,

When I use:

extensions:
- Contributte\FormMultiplier\DI\MultiplierExtension

or

extensions:
replicator: Contributte\FormMultiplier\DI\MultiplierExtension

or for older version

extensions:
- WebChemistry\FormMultiplier\DI\MultiplierExtension

or

extensions:
replicator: WebChemistry\FormMultiplier\DI\MultiplierExtension

I got error after install 3.0.6 always (and older version too):
Class 'Contributte\FormMultiplier\DI\MultiplierExtension' not found

Why?
Help, please.

My nette composer:

"require": {
"php": ">5.6.0",
"nette/application": "^2.4.4",
"nette/bootstrap": "^2.4.3",
"nette/caching": "^2.5",
"nette/database": "^2.4",
"nette/di": "^2.4",
"nette/finder": "^2.4",
"nette/forms": "^2.4",
"nette/http": "^2.4",
"nette/mail": "^2.4",
"nette/robot-loader": "^2.4.4",
"nette/safe-stream": "^2.3",
"nette/security": "^2.4",
"nette/utils": "^2.4",
"latte/latte": "^2.4",
"tracy/tracy": "^2.4",
"contributte/recaptcha": "^3.1",
"janmarek/webloader": "dev-master",
"joseki/webloader-filters": "^1.1",
"oyejorge/less.php": "v1.7.0.14",
"leafo/scssphp": "^0.8.2",
"nextras/mail-panel": "^2.4",
"matthiasmullie/minify": "^1.3",
"robmorgan/phinx": "^0.10.7",
"dg/ftp-deployment": "^2.9",
"h4kuna/gettext-latte": "dev-master",
"contributte/application": "^0.3.2",
"ublaboo/datagrid": "^5.7",
"o5/grido": "^3.0",
"ipub/visual-paginator": "@dev",
"nasext/visual-paginator": "^3.1",
"contributte/forms-multiplier": "^3.0"
},
"require-dev": {
"nette/tester": "^2.0"
},
"minimum-stability": "dev",
"prefer-stable": true,
"config": {
"platform": {
"php": "7.1"
}
}

With default values remove buttons are missing

Hello,
i have problem with remove buttons with default values. When i create Multiplier with default values, remove buttons are missing...
When i add new container (inputs) with add button and redraw it with ajax all remove buttons are at the form.

I am not sure, but i think it could be a bug.

How to set defaultValues for two nested multipliers? Possible bug

Hello, i have problem with setting default values into two multipliers (second multiplier is inside first one).

i have this kind of array with default values:

$defaultValues = array(
                    0 => array(
                        'input1' => 'val1',
                        'input2' => 'val2',
                        'multiplier_child' => array(
                            0 => array(
                                'input3' => 'val3'
                            ),
                            1 => array(
                                'input3' => 'val4'
                            )
                        )
                    ),
                    1 => array(
                        'input1' => 'val5',
                        'input2' => 'val6',
                        'multiplier_child' => array(
                            0 => array(
                                'input3' => 'val7'
                            )
                        )
                    )
                );

Default values are set into input1 and input2 correctly, but input3 is empty at both containers.

Do i have right array for default values?

Method applyDefaultValues can't set default values

Method applyDefaultValues can't set default values becouse method Nette\Forms\Form::isSubmitted() returns true, when dealing with POST request.

The solution would be dummy Form instance. This worked for me.

class FakeForm extends Nette\Forms\Form
{
	public function getHttpData($type = null, $htmlName = null)
	{
	}
}

class Multiplier extends Container
{
	... code

	protected function applyDefaultValues(Container $container)
	{
		$factoryContainer = (new FakeForm())->addContainer('void');
		$this->fillContainer($factoryContainer);

		foreach ($factoryContainer->getControls() as $name => $control) {
			/** @var IControl $component */
			$component = $container->getComponent($name, false);
			if ($component) {
				$component->setValue($control->getValue());
			}
		}
	}

	... code
}

Add/remove buttons do not work when form is attached in constructor

The multiplier does not work when we create our form like this:

public function createComponentAbcForm(string $name) : AbcForm
    {
        $form = new AbcForm($this, $name);
        $form->createElements($this->getAction());
        $form->onSuccess[] = [$this, "baseFormSuccess"];
        return $form;
    }

imho because the form is already attached in here so the onAnchor is never called

if ($obj instanceof \Nette\Application\UI\Form) {
    $obj->onAnchor[] = function (): void {
	$this->whenAttached();
    };
}
$obj->onRender[] = function (): void {
	$this->whenAttached();
};

and the call during onRender is too late for the buttons to react properly and the form goes to onSuccess instead (the submittedBy is never set by the buttons in this case).

I tried fixing it by calling whenAttached() directly when the form is already anchored but that broke something else and the add button was not rendered at all because it was not yet configured.

Missing macros

Folder Macros is missing in release 2.0.1. I just let you know ;)

Type error when adding a copy containing another multiplier

Hi, I have found a bug on line https://github.com/contributte/forms-multiplier/blob/master/src/Multiplier.php#L297
When adding a copy with another multiplier, attribute $values contains object ArrayHash instead of array causing TypeError (ComponentResolver requires array as second parameter). This minor change should fix that:
$resolver = new ComponentResolver($this->httpData, (array) $this->values, $this->maxCopies, $this->minCopies);

$container->setPrompt('') makes a problem on add new copy

$container->setPrompt('') makes a problem on add new copy. Problem is only with comboboxes. During adding the copy are setting the default values into the comboboxes. The default value is null, when no item is selected.

There is catched the following exception:

Nette\InvalidArgumentException
Value '' is out of allowed set [12, 14, 15, 16, 17, 20, 21, 22, 24, 25, 28, 29, 41, 44, 46, 47, 57,...] in field 'wms_wu_model_id'

Add/Delete Button validation

I have:

Composer.json

"require": {
		...
		"webchemistry/forms-multiplier": "dev-master"
	},

updated at e998393

Form factory:

/** @var \WebChemistry\Forms\Controls\Multiplier $multiplier */
$multiplier = $form->addMultiplier('rows', function (Nette\Forms\Container $container, Nette\Forms\Form $form) {
		
	$container->addText('name', 'Name')
		->setRequired('Please, fill name');
}

$multiplier->addCreateButton('Add row', 1, function (SubmitButton $submitter) {
	$submitter->setValidationScope(FALSE);
});

In generated HTML code, there is

<input type="submit" name="rows[multiplier_creator]" value="Add row" formnovalidate="" data-nette-validation-scope="[&quot;rows&quot;]" class="ajax prepareLines">

But when I click twice od add button, nette $form->hasErrors() contains validation error 'Please, fill name'

I expect no validation on add button, user can add multiple rows and then fill them...

Can't delete last element (v3.0.2)

Problem was on this version: v3.0.2
Composer: "webchemistry/forms-multiplier": "^3.0"

When I want to remove all elements with remove button, it's impossible to do that with the last element.

Component with name 'multiplier_remover' already exists.
Throws: Nette\InvalidStateException

`/** @var \WebChemistry\Forms\Controls\Multiplier $multiplier */
$multiplier = $form->addMultiplier('multiplier', function (Nette\Forms\Container $container, Form $form) {
$container->addTextArea('value');
}, 0);

    $multiplier->setValues($defaultValues);
    $multiplier->addCreateButton("Add")->addClass('btn_add');
    $multiplier->addRemoveButton("Remove")->addClass('btn_remove');

On version 2.x it works.

Problem with container removing after in 3.0.5

Hello,
i have got problem with container removing in 3.0.5 (3.0.4 works fine).

remove button definition in form component:

$groups->addRemoveButton('', function (Nette\Forms\Controls\SubmitButton $submitter) use ($presenter, $groupObject) {
                                $submitter->setHtmlAttribute('class','btn-danger btn-sm fas fa-minus ajax');
                                $submitter->setHtmlAttribute('data-toggle', 'confirmation');
                                $submitter->setHtmlAttribute('data-title', 'Odstranit?');
                                $submitter->setHtmlAttribute('data-btn-ok-label', 'Ano');
                                $submitter->setHtmlAttribute('data-btn-ok-class', 'btn btn-success btn-sm');
                                $submitter->setHtmlAttribute('data-btn-cancel-label', 'Ne');
                                $submitter->setHtmlAttribute('data-btn-cancel-class', 'btn btn-danger btn-sm');
                                $submitter->setOption('group', $groupObject->getType());
                                $submitter->onClick[] = function () use ($presenter) {
                                    /** @var \Nette\Application\UI\Presenter $presenter */
                                    $presenter->redrawControl('segmentForm');
                                };
                            });

                            $signalName = $this->getUniqueId() . '-' . $name . '-' . $groups->getName();
                            if (is_array($this->getPresenter()->getSignal()) && $this->getPresenter()->getSignal()[1] === 'load' && preg_match('#' . $signalName . '-([0-9]+)#', $this->getPresenter()->getSignal()[0], $matches)) {
                                $groups->addCopy($matches[1]);
                            }

component form template:

{snippet segmentForm}
    {form segmentForm}
          // some logic for render
    {/form}
{/snippet}

Problem is snippet segmentForm is not refreshed.

Thank you for check.

Component 'multiplier_remover' is not attached to 'Nette\Forms\Form'

When using manual rendering of forms with groups and iterating over groups, I am getting InvalidStateException: Component 'multiplier_remover' is not attached to 'Nette\Forms\Form'

...
$form->addGroup("TEST");
$multi = $form->addMultiplier("multi", function(\Nette\Forms\Container $container, \Nette\Application\UI\Form $form) {
            $container->addText("a", "A");
        }, 1);

$multi->addCreateButton("Add");
$multi->addRemoveButton("Remove");
....

Latte:

{form testForm}
    {foreach $form->getGroups() as $groupName => $group}
        {foreach $group->getControls() as $name => $input}
             {input $input}
        {/foreach}
    {/foreach}
{/form}

This error doesn't happen when the form is rendered automatically or you itarate right over $form->getControls()

Filling in multiple values

Hi. Thanks for good work. I do have one problem.

I cannot figured out, how to fill in values. For example, when I want to edit previously added values. When I want edit users name and surname I try something like:

// form definition
$form->addMultiplier('users', function (\Nette\Forms\Container $container) {
$container->addText('name');
$container->addText('surname');
});

//action edit
foreach ($users as $user) {
$form['users'][$user->id]['name']->setDefaultValue($user->name);
$form['users'][$user->id]['surname']->setDefaultValue($user->surname);
}

But with no luck and the is nothing in documentation. Thanks.

Custom container

I can try prepare PR & test for using custom Container with multiplier.

image

Desired result will be definition custom class via extension parameters. Otherwise multiplier use nette container.

multiplier:
  containerClass: \Your\Class\Custom;

What is your opinion?

Missing "getCreateButtons" method

Hi,

I get this error: Call to undefined method WebChemistry\Forms\Controls\Multiplier::getCreateButtons(), did you mean addCreateButton()? when using btnCreate macro.
It looks like the getCreateButtons method isn't anywhere in the package.

Can't use addConditionOn() when creating Multiplier

Code:

$disks = $form->addMultiplier('disks', [$this, 'addDisk'], 0);

public function addDisk(Container $container): void
{
    $container->addText('size', 'Size')
        ->addConditionOn($container->form['brand'], Form::EQUAL, 'kvm')
            ->setRequired();
}

Error:

Nette\InvalidStateException
Component '' is not attached to 'Nette\Forms\Form'.

Support for nette/forms ^3.0

After composer update

Problem 1
    - contributte/forms-multiplier v3.0.0 requires nette/forms ^2.4 -> satisfiable by nette/forms[v2.4.x-dev].
    - contributte/forms-multiplier v3.0.1 requires nette/forms ^2.4 -> satisfiable by nette/forms[v2.4.x-dev].
    - contributte/forms-multiplier v3.0.2 requires nette/forms ^2.4 -> satisfiable by nette/forms[v2.4.x-dev].
    - contributte/forms-multiplier v3.0.3 requires nette/forms ^2.4 -> satisfiable by nette/forms[v2.4.x-dev].
    - contributte/forms-multiplier v3.0.4 requires nette/forms ^2.4 -> satisfiable by nette/forms[v2.4.x-dev].
    - contributte/forms-multiplier v3.0.6 requires nette/forms ^2.4 -> satisfiable by nette/forms[v2.4.x-dev].
    - contributte/forms-multiplier v3.x-dev requires nette/forms ^2.4 -> satisfiable by nette/forms[v2.4.x-dev].

Thank you very much :)

Default number of containers and remove button

Hello. For example. I have 3 multipliers at one page (one form). All multipliers have 1 container by default.
None of the containers has remove button (thats right). When i click on the add button on one of the multipliers, it will add and next container and it will add 1 remove button to the each container (thats right too) BUT also it will add remove buttons to all previous multipliers.

Example 1:
default state:

multiplier1
-- container1 - NO remove button
multiplier2
-- container1 - NO remove button
multiplier3
-- container1 - NO remove button

I will click on add button on container1 of multiplier3
result is:

multiplier1
-- container1 - remove button
multiplier2
-- container1 - remove button
multiplier3
-- container1 - remove button
-- container2 - remove button

Example 2:
default state:

multiplier1
-- container1 - NO remove button
multiplier2
-- container1 - NO remove button
multiplier3
-- container1 - NO remove button

I will click on add button on container1 of multiplier2
result is:

multiplier1
-- container1 - remove button
multiplier2
-- container1 - remove button
-- container2 - remove button
multiplier3
-- container1 - NO remove button

This is very interesting and i dont know what problem is. This behavor is only at empty inputs. When i use default values, everything is fine.

Any idea?

Thank you very much

Ajaxification

Is there some way how to ajaxify adding/removing of rows?

addRemoveButton calling onSuccess[]

Hello,

I have problem with addRemoveButton. I add it to my multiplier but after clicked this button its calling onSuccess[] callback. Im using dev-master version.

public function create($view, $parameter, callable $onSuccess): Form
    {
        $form = $this->formFactory->create();
        $copies = 1;
        $maxCopies = 5;

        $form->addText('name', 'Názov:')
            ->setRequired('Prosím vložte názov.');

        $form->addText('url', 'Odkaz:')
            ->setRequired('Prosím vložte Odkaz.');

        $multiplier = $form->addMultiplier('multiplier', function (Container $container, \Nette\Forms\Form $form) {
            $container->addText('feeName', 'Názov poplatku:');
            $container->addInteger('feeAmount', 'Výška poplatku (%):');
        }, $copies, $maxCopies);

        $multiplier->addCreateButton('Zadat další poplatok');
        $multiplier->addRemoveButton('Odstranit poplatok');

        if ($view != 'edit') {
            $form->addSubmit('submit', 'Vytvoriť burzu');
        } else {
            $form->addSubmit('submit', 'Editovať burzu');
        }

        /**
         * @param Form $form
         * @param ArrayHash $values
         */
        $form->onSuccess[] = function (Form $form, ArrayHash $values) use ($view, $parameter, $onSuccess) {

            die('pič');
            $onSuccess();
        };

        return $form;
    }
{form marketForm, class=> "form-horizontal"}

                <div class="form-group">
                    <label class="col-lg-2 control-label">{label name}</label>
                    <div class="col-lg-10">
                        {input name, class=> "form-control"}
                    </div>
                </div>

                <div class="form-group">
                    <label class="col-lg-2 control-label">{label url}</label>
                    <div class="col-lg-10">
                        {input url, class=> "form-control"}
                    </div>
                </div>

                <div class="hr-line-dashed"></div>

                <div n:multiplier="multiplier">
                    <div class="form-group">
                        <label class="col-lg-2 control-label">{*{label feeName}*}</label>
                        <div class="col-lg-10">
                            {input feeName, class=> "form-control"}
                        </div>
                    </div>

                    <div class="form-group">
                        <label class="col-lg-2 control-label">{*{label feeAmount}*}</label>
                        <div class="col-lg-10">
                            {input feeAmount, class=> "form-control"}
                        </div>
                    </div>
                    {btnRemove multiplier}
                </div>
            {btnCreate multiplier, class => myClass}

                <div class="hr-line-dashed"></div>

                <div class="row form-group">
                    <div class="col-sm-4 col-sm-offset-2">
                        {input submit, class=>"btn btn-primary"}
                    </div>
                </div>
            {/form}

Form is not anchored and therefore can not determine whether it was submitted.

Hello,
i am using your hack to work with NasExt/DependentSelectBox (it was sloved here #12 ), but with latest version i am getting this error again: Form is not anchored and therefore can not determine whether it was submitted.
So probably its something broken. Can you help me please?
The hack is this code:

$signalName = $this->getUniqueId() . '-' . $name . '-' . $groups->getName();
if (is_array($this->getPresenter()->getSignal()) && $this->getPresenter()->getSignal()[1] === 'load' && preg_match('#' . $signalName . '-([0-9]+)#', $this->getPresenter()->getSignal()[0], $matches)) {
    $groups->addCopy($matches[1]);
}

multiplier with dependent select

Hi, I have a little problem. I want to multiply NasExt/DependentSelectBox. But I only got error Component 'item' is not attached to 'Nette\Forms\Form'. Thanks for any help.

$form->addSelect('event','Event',$firstInput)->setRequired(TRUE)->setPrompt("Select event");

    $form->addDependentSelectBox('site', 'Site:', array($form['event']), function ($values) {
        $data =  new DependentSelectBoxData();
        if (isset($values['event'])) {
            $dataSite = $this->siteFacade->getNamesByEventId($values['event'],$this->locale);
            return $data->setItems($dataSite);
        }else{
            return $data;
        }
    })->setPrompt('- Select Site-')->setRequired()->setDisabledWhenEmpty(TRUE);

    $form->addMultiSelect('members','Members',$members)->setRequired(TRUE);


    $multiplier = $form->addMultiplier('multiplier', function (Nette\Forms\Container $container, Nette\Forms\Form $form) {
        $container->addDependentSelectBox('item', 'Item:', array($form['event']), function ($values) {
            $data =  new DependentSelectBoxData();
            if (isset($values['event'])) {
                $dataItems = $this->optItemFacade->getOptItemsByEventId($values['event'],$this->locale);
                return $data->setItems($dataItems);
            }else{
                return $data;
            }
        })->setPrompt('-Select Item-')->setDisabledWhenEmpty(TRUE);
        $container->addInteger('count','count');
    }, 0, 15);
    $multiplier->addCreateButton('Add');
    $multiplier->addRemoveButton('Remove');

Nested multiplier bugs

Hi, I use nested multiplier in another multiplier, where both multipliers (inner and outer) have been set the copy number to 1 (default) and I found 2 bugs:

  • The nested (inner) multiplier has container containing inputs with some defaultValues set by BaseControl::setDefaultValue(). However, when I add a new copy by multiplier submit create button, the inputs of the new copy does not have its default values filled (only the first default copy does have)

  • When I add a new copy of the outer multiplier by its submit create button, the inner multiplier of the new outer multiplier copy does not have created its default copy (like the copy number being ignored), however the first default copy of the outer multiplier does have its outer multiplier with its default copy created

Group name

Hello,
in the Multiplier container there is no group name set in the form with:
$form->addGroup('GroupName');

So in the template when i call this: $control->getCurrentGroup()->getOption('label'); i get error there is no group option.

Is any way to add this feature?

Thank you :)

Missing support for `createOne`

There is method createOne in Kdyby/FormsReplicator that allow to work with containers by your own.

In our project there is something like:

<?php

namespace App;

use Nette\Application\UI\Form;

class TestForm extends Form {

	public function __construct() {
		$this->addDynamic('params', function(Container $container) {
			$container->addText('name', 'Název obecného parametru');
		}, 0);
	}

	public function loadParams() {
		$params = [
			'Parametr 1',
			'Parametr 2',
			'Parametr 3',
		];

		foreach ($params as $id => $name) {
			$container = $this['params']->createOne($id);
			$container['name']->caption = $name;
		}
	}

}

There is method addCopy in WebChemistry/Multiplier that work almost same.

But it is protected.

Will it be possible to make this method public by default?

Or,is there any other way for manually adding values in dynamic container and work with each one?

Jak správně předat setDefaults z Action

Čau,
mám dotaz snažím se přijít na to jak správně z Action metody nastavit multiplieru defaultní hodnoty tak jako se klasicky dělá.

viz...

 $this['eventTermForm']->setDefaults([
                    'terms_id' => $terms->terms_id,
                    'event_id' => $terms->event_id,
                    //'date' => $terms->date,
                    'price' => $terms->price,
                    'capacity' => $terms->capacity
                ]);

A formulář

protected function createComponentEventTermForm() {
        $copies = 1;
        $maxCopies = 7;
        $form = new Form();
        $form->addHidden('terms_id');
        $form->addSelect('event_id', '', $this->termsRepository->getSelectEvent())
            ->setPrompt('Vyberte Lekci')
            ->setRequired('Lekce je povinná!');
        $multiplier = $form->addMultiplier('multiplier', function (\Nette\Forms\Container $container, \Nette\Forms\Form $form) {
            $container->addText('date')
                ->setRequired('Datum je povinné!');
        }, $copies, $maxCopies);
        $multiplier->addCreateButton('Přidat další datum')
            ->addClass('btn btn-primary');
        $multiplier->addRemoveButton('Odstranit datum')
            ->addClass('btn btn-danger');
        $form->addText('price')
            ->setRequired('Cena je povinná!');
        $form->addText('capacity')
            ->setRequired('Kapacita je povinná!');
        $form->addCheckbox('all');
        $form->addSubmit('send');
        $form->onSuccess[] = [$this, 'eventTermFormSucceeded'];

        return $form;
    }

Hledal jsem nějaké řešení ale nic moc jsem nenašel díky moc...

Component 'dependent_select' is not attached to 'Nette\Forms\Form'

Hello,
i have problem with using multiplier and Nasext/DependentSelectBox. When i want to add new set of attributes with add button, i got this error: Component 'dependent_select' is not attached to 'Nette\Forms\Form'

Here is my testing component:

<?php

namespace App\Forms;

use NasExt\Forms\DependentData;
use Nette;
use Nette\Application\UI\Control;
use Nette\Application\UI\Form;
use WebChemistry\Forms\Controls\Submitter;


/**
 * Class MultiplierDependentFormControl
 * @package App\Forms
 */
class MultiplierDependentFormControl extends Control {

    public $onSave = array();

    /**
     * MultiplierDependentFormControl constructor.
     */
    public function __construct() {
        parent::__construct();
    }

    /**
     *
     */
    protected function beforeRender() {
        parent::beforeRender();
        if($this->isAjax()) $this->template->getLatte()->addProvider('formsStack', [$this['multiplierDependentForm']]);
    }

    /**
     *
     */
    public function render() {
        $this['multiplierDependentForm']->render();
        //$this->template->setFile(__DIR__ . '/multiplierDependentForm.latte');
        //$this->template->render();
    }

    /**
     * @return Form
     */
    public function createComponentMultiplierDependentForm() {

        $form = new Form;
        $copies = 1;
        $maxCopies = 10;

        $array = array(
            1 => 'jedna',
            2 => 'dva',
            3 => 'tři',
        );

        $lookup_data = array(
            1 => array (
                1 => '1/1',
                2 => '1/2',
                3 => '1/3',

            ),
            2 => array (
                1 => '2/1',
                2 => '2/2',
                3 => '2/3',
            ),
            3 => array (
                1 => '3/1',
                2 => '3/2',
                3 => '3/3',
            ),
        );

        $multiplier = $form->addMultiplier('multiplier', function (Nette\Forms\Container $container, Nette\Forms\Form $form) use ($array, $lookup_data) {
            $container->addSelect('array', 'Array', $array)
                ->setPrompt('--- Select ---');

            $container->addDependentSelectBox('dependent_select', 'Dependent select:', $container['array'])
                ->setDependentCallback(function ($values) use ($array, $lookup_data) {
                    $data = new DependentData;

                    if ($values['array']) {
                        $data->setItems($lookup_data[$values['array']])->setPrompt('---');
                    } else {
                        $data->setItems(array())->setPrompt('---');
                    }

                    return $data;
                })
                ->setPrompt('--- Select array first ---');

        }, $copies, $maxCopies);

        $presenter = $this;

        $multiplier->addCreateButton('+', 1, function (Submitter $submitter) use ($presenter) {
            //$submitter->setHtmlAttribute('class', 'ajax');
            $submitter->onClick[] = function () use ($presenter) {
                /** @var \Nette\Application\UI\Presenter $presenter */
                $presenter->redrawControl('multiplierDependentForm');
            };
        });

        $multiplier->addRemoveButton('-', function (Nette\Forms\Controls\SubmitButton $submitter) use ($presenter) {
            //$submitter->setHtmlAttribute('class', 'ajax');
            $submitter->onClick[] = function () use ($presenter) {
                /** @var \Nette\Application\UI\Presenter $presenter */
                $presenter->redrawControl('multiplierDependentForm');
            };
        });

        $form->addProtection('Error, try again!');

        $form->addSubmit('save', 'Uložit')
            ->setAttribute('class', 'btn-primary')
            ->setAttribute('id','submit')
            ->onClick[] = array($this, 'formSucceeded');

        return $form;
    }


    /**
     * @param $form
     * @param $values
     */
    public function formSucceeded($form, $values) {

        $this->onSave();
    }


}//class

/**
 * Interface IMultiplierDependentFormControl
 * @package App\Forms
 */
interface IMultiplierDependentFormControl {

    /**
     * @return MultiplierDependentFormControl
     */
    public function create();
}

event onCreate is not called on new container

Simple code:

$form['registerConfigForm']->onCreate[] = function (Nette\Forms\Container $container) { $container['item_id']->setValue($id++); };

It fills correctly field item_id, but when you want to add another container with button $multiplier->addCreateButton('Create');, field item_id is not filled.

Špatné vygenerování html id

Kód:

$form->addMultiplier('a', function (Container $container): void {

	$b = $container->addSelect('b', null, [1 => '1', 2 => '2']);

	$c = $container->addSelect('c', null, [1 => '1']);

	$b->addCondition(Form::NOT_EQUAL, 1)
		->toggle($c->getHtmlId());

}, 2);

Vygeneruje pro všechny inputy c stejný html id.
Místo frm-form-a-0-c se vygeneruje frm-c pro všechny inputy.
Zpsobí to, že pokud mám jeden ze selectu b mimo hodnotu 1 všechny inputy c se zobrazí.

Render:

<div n:multiplier="a">
	{input b}
	{input c}
</div>

SetDefaults with UI/Form

I dont want be annoying. This doesnt create "defaults" containers.

public function actionDefault()
    {
        $this['form']->setDefaults([
            'multiplier' => [
                '0' => ['text' => 'sorry'],
                '1' => ['text' => 'jako']
            ]
        ]);
    }

    protected function createComponentForm()
    {
        $form = new Nette\Application\UI\Form;
        $copies = 0;
        $maxCopies = 10;

        $multiplier = $form->addMultiplier('multiplier', function (Nette\Forms\Container $container, Nette\Forms\Form $form) {
            $container->addText('text', 'Text');
        }, $copies, $maxCopies);

        $multiplier->addCreateButton('Add')
                ->addClass('btn btn-primary');
        $multiplier->addRemoveButton('Remove')
                ->addClass('btn btn-danger');

        return $form;
    }

Exception of validation

Hi, I should ask how can I turn off or bypass that when adding a new line using
$multiplier->addCreateButton('Add');
will not validate my entire form?

Something like the classic form of the function?
->setValidationScope()

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.