Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Dynamically adding input fields in Yii2

I'm having some trouble with forms in Yii2. I need to create a form which includes three dropdown menus which ask the user what time(s) in a week work best for him or her. The first menu would be days of the week, and the next two would be start and end times.

But my project is more ambitious than that. I need to also allow the user to specify any time configuration, and so the form must be expanded and made dynamic, allowing the user to add more dropdown menus to the form to specify more times.

I've tried a lot of solutions, but the trouble seems to lie in having user-created input fields. I believe there was a way to do this in Yii 1, but Yii 2 was apparently such a code overhaul that old workarounds are rarely useful. I've investigated many extensions, particularly Krajee's extensions, and though many of them are very pretty and user-friendly, they don't offer dynamic field creation. I've tried some hacks myself, but nothing has worked, and I'm wondering if there's a way at all to create a form with a dynamic number of input fields in Yii 2. If not, I'm tempted to just write some simple Javascript and Php outside of Yii to get the job done, but I'd like to stay within the framework.

like image 272
richp32 Avatar asked Sep 17 '14 20:09

richp32


2 Answers

Its not what complex its looks like..

There are lots of solutions out there and you may find many examples..

see these example i've found for you.

See this fully working example where you can multiple address and you can change these fields to match fields what you need.

http://wbraganca.com/yii2extensions/dynamicform-demo1/create

https://github.com/wbraganca/yii2-dynamicform

exmaple dynamic field creation with yii2

like image 83
dev.meghraj Avatar answered Oct 18 '22 12:10

dev.meghraj


If anyone is here in 2019, have a look at Yii2 documentation - Here

$('#contact-form').yiiActiveForm('add', {
    id: 'address',
    name: 'address',
    container: '.field-address',
    input: '#address',
    error: '.help-block',
    validate:  function (attribute, value, messages, deferred, $form) {
        yii.validation.required(value, messages, {message: "Validation Message Here"});
    }
});

To enable client validation for these fields, they have to be registered with the ActiveForm JavaScript plugin

like image 30
Eddie Avatar answered Oct 18 '22 11:10

Eddie