Skip to content

Instantly share code, notes, and snippets.

@tonysm
Last active June 3, 2022 13:00
Show Gist options
  • Save tonysm/4955670 to your computer and use it in GitHub Desktop.
Save tonysm/4955670 to your computer and use it in GitHub Desktop.
dynamically creating inputs with CakePHP and jQuery
<?php
echo $this->Form->create('Usuario');
echo $this->Form->input('Usuario.0.nome', array('div'=>array('id' => 'botoes-wrap')));
echo $this->Html->link('mais um nome', '#botao-add-nome', array('id' => 'bota-add-nome'));
echo $this->Form->submit('Enviar');
echo $this->Form->end();
echo $this->Html->script(array(
'http://code.jquery.com/jquery.min.js',
'usuarios/index'
));
?>
<script type="text/template" id="template-inputs">
<?php echo $this->Form->input('Usuario.::num.nome', array('div' => false, 'label' => '::plus° Nome')); ?>
</script>
;(function($, window, document, undefined) {
$(document).ready(function() {
var botaoAdd = $('#bota-add-nome'),
botoesWrap = $('#UsuarioIndexForm').find('#botoes-wrap'),
template = $.trim($('#template-inputs').html()),
nextItem = 1;
function addNewInputToTheForm() {
var newItemHtml = template.replace(/::num/g, nextItem++)
.replace(/::plus/, nextItem);
botoesWrap.append(newItemHtml);
}
botaoAdd.on('click', function(e) {
e.preventDefault();
addNewInputToTheForm();
});
});
})(jQuery, window, document);
<?php
/**
* Controller de usuários
*/
class UsuariosController extends AppController
{
public function index()
{
if(isset($this->request->data) && $this->request->is('post')) {
debug($this->request->data);
}
}
}
@joaocaemerer
Copy link

Olá, está funcional este código ?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment