I'm working with bootbox to render a forms with symfony 2. So I've a one trouble when I wanna change the content dynamically I don't know how.
So this is that I wanna
<button class="btn btn-primary btn-new" data-toggle="modal" data-target="#agregarRonda">
Add My Entity
</button>
<div style="display: none;" class="modal fade" id="agregarRonda" tabindex="-1" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal" aria-hidden="true">×</button>
<h4 class="modal-title" id="myModalLabel">Add my Entity</h4>
</div>
<div class="modal-body">
{% embed "projete:MyEntity:newMyEntity.html.twig" %}
{% endembed %}
</div>
</div>
</div>
</div>
2.When I render a Form newMyentity.html.twig this has a button that redirecting to this method inside of my controller on symfony like:
public function createMyEntityAction(Request $request)
{
$user = $this->get('security.context')->getToken()->getUser();
$entity = new MyEntity();
$form = $this->createMyEntityForm($entity);
$form->handleRequest($request);
if ($form->isValid())
{
if( ifNotExist( $entity->getDescription() ) )
{
//Do the right things
}
else{
/*
* Return content to the modal dialog and don't hide modal dialog?
*/
}
}
}
So, I call a method ifNotExist to check somethings.If return false I wish to send content to the modal dialog without hide the modal dialog and modify the content.
How can I do it?
Thanks.
You can do something like this:
public function createMyEntityAction(Request $request)
{
$user = $this->get('security.context')->getToken()->getUser();
$entity = new MyEntity();
$form = $this->createMyEntityForm($entity);
if ($request->getMethod()=="POST"){
$form->handleRequest($request);
if ($form->isValid())
{
$em = $this->getDoctrine()->getManager();
$em->persist($entity);
$em->flush();
return new Response($entity->getId(),201);
}
}
return $this->render('yourFormTemplate.html.twig', array('form' => $form->createView() );
}
Your entity:
use Symfony\Component\Validator\Constraints as Assert;
...
/**
* MyEntity
* @ORM\Entity()
* @ORM\Table()
*/
class MyEntity
{
...
/**
*
* @Assert\NotBlank(message ="Plz enter the description")
*/
private $description;
...
}
Your JS:
$('#yourAddBtnId').on('click', function(){
var $modal = $('#yourModalId')
$.get("yourURL", null, function(data) {
$modal.find('modal-body').html(data);
})
// create the modal and bind the button
$('#yourModalId').dialog({
buttons: {
success: {
label: "Save",
className: "btn-success",
callback: function() {
that = this;
var data = {};
// get the data from your form
$(that).find('input, textarea').each(function(){
data[$(this).attr('name')] = $(this).val();
})
// Post the data
$.post( "yourURL", function(data , status) {
if ( "201" === status){
$modal.modal('hide');
}
else {
$modal.find('modal-body').html(data);
}
});
}
}
});
});