Re: [web2py] Open form's view on a modal

122 views
Skip to first unread message
Message has been deleted

Christian Varas

unread,
Oct 17, 2019, 9:14:35 AM10/17/19
to web...@googlegroups.com
Hi, for that I do the following:

In the controller I set the form

agregar_ruta = SQLFORM.factory(Field("nombre_ruta", requires=IS_NOT_EMPTY()),

                                               Field("Modalidad", default=modalidades[1],requires=IS_IN_SET(modalidades)),

                                               Field("Tipo", default='Monolargo', requires=IS_IN_SET(tipo)),

                                               Field("Grado", default=grados_roca[2], requires=IS_IN_SET([], multiple=False)),

                                               Field("Artifo", label="Artifo?", default=grado_artifo[0], requires=IS_IN_SET(grado_artifo)),

                                               Field("Zona", label="Zona (no olvides seleccionar la zona)",default=zonas_list[0],

                                                     requires=IS_IN_SET(zonas_list, zonas_list_name)),

                                               Field("Observacion", 'text', length=300,

                                                     default='No se han registrado observaciones', label="Observaciones"),

                                               _name="agregar_ruta",

                                               submit_button="Agregar",

                                               )


return dict(agregar_ruta=agregar_ruta)


then the view you fill the modal with the form

In the controller I set the form

<div class="modal fade" id="modal_agregar_ruta" role="dialog" aria-labelledby="myModalLabel">

    <div class="modal-dialog" role="document">

        <div class="modal-content">

                <div class="modal-header">

                    <button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">×</span></button>

                    <h4 class="modal-title" id="myModalLabel">Agregar Nueva Ruta</h4>

                </div>

                <div class="modal-body">

                    {{=agregar_ruta}}


                </div>


        </div>

    </div>

</div>


and a small script that brings the modal up when a certain button is clicked

<script>

function agregarRuta() {
        $('#modal_agregar_ruta').modal('show');
    };
</script>

that's turns in this:
image.png
btw: if you have multiples forms in this view/function you will have to process them specifically, like this: 

if agregar_ruta.process(formname='agregar_ruta').accepted:
       do something

if agregar_ruta.process(formname='agregar_ruta').accepted:

Cheers.

El mié., 16 oct. 2019 a las 18:39, Cristina Sig (<kryst...@gmail.com>) escribió:
Hello,

I have this function that helps me to edit a record from DB.
 


def studentUpdate():
       
return dict(formCarreraUpdate=crud.update(db.Student,request.args(0),message=T("Done!")))


and would like to open it's view on a modal (popup style) on the same page that I'm working. Something like the image. I tried but fail because the form it doesn't send the data back to the server. Is there any friendly way to achieve that?

Thanks!!

Captura de Pantalla 2019-10-16 a la(s) 18.34.35.png


--
Resources:
- http://web2py.com
- http://web2py.com/book (Documentation)
- http://github.com/web2py/web2py (Source code)
- https://code.google.com/p/web2py/issues/list (Report Issues)
---
You received this message because you are subscribed to the Google Groups "web2py-users" group.
To unsubscribe from this group and stop receiving emails from it, send an email to web2py+un...@googlegroups.com.
To view this discussion on the web visit https://groups.google.com/d/msgid/web2py/25f2fab1-189d-4482-955b-db0cca4ca717%40googlegroups.com.

Cristina Sig

unread,
Oct 18, 2019, 6:01:30 PM10/18/19
to web...@googlegroups.com
Thanks for your explanation,

I'm a newbie on web2py so I have some doubts.
Do you set your modal and script that calls that modal on the main page? or do you call it from a different view page?
I'm a little bit confused

lu ond

unread,
Oct 18, 2019, 8:40:22 PM10/18/19
to web2py-users
Dear Cristina,
I make the modal in the main page and use components (LOAD()) to submit the forms. This way, each form shall have its own controller function (for instance, your_form) and view ('your_form.load'). The javascripts are inserted by the form functions (the component). I use response.js. As an example of main page:
def show_entities():
    response.title = 'Home'
    projects_list = []
    nav_bar = []
    project_name = ''
    form_ret = None
    form_det = None
    form_ent = None
    table_ent = None
    if request.args:
        project_id = request.args(0cast=int)
        project_name = db.project(project_id).project_name
        nav_bar = gera_nav_bar(project_id)
        response.js = '$("#entity_modal").modal("show");'
        form_ret = LOAD('default''cru_ret.load',
                        args=request.args(0), ajax=Truetarget='form_ret')
        form_det = LOAD('default''cru_det.load',
                        args=request.args(0), ajax=Truetarget='form_det')
        form_ent = LOAD('default''cru_ent.load',
                        args=request.args(0), ajax=Truetarget='form_ent')
        table_ent = LOAD('default''table_entities.load',
                         args=request.args(0), ajax=Truetarget='table_ent')
    else:
        projects_query_results = db(db.project.id > 0).select(orderby=db.project.id)
        projects_list = cria_tabela_projetos(projects_query_results, 'show_entities')
    return dict(projects_list=projects_list,
                project_name=project_name,
                nav_bar=nav_bar,
                form_ret=modal_helper('ret_modal''Record Entity Type', form_ret),
                form_det=modal_helper('det_modal''Data Entity Type', form_det),
                form_ent=modal_helper('entity_modal''Entity', form_ent),
                table_ent=table_ent)

Here an example of component controller function:
def cru_ent():
    table_style = 'bootstrap4_stacked'
    if len(request.args) > 1# update entity button
        entity_id = request.args(1cast=int)
        form = SQLFORM(db.entity, db.entity(entity_id), formstyle=table_style)
        response.js = '$("#entity_modal").modal("show");'
    elif request.args: # only project information
        project_id = request.args(0cast=int)
        db.entity.project_id.default = project_id
        form = SQLFORM(db.entity, formstyle=table_style)
        if request.vars.reload_div:
            response.js = '$("#entity_modal").modal("show");'
    else# general call even without project
        form = SQLFORM(db.entity, formstyle=table_style)
    if form.process().accepted:
        response.flash = 'New Entity added!'
        if request.vars.reload_div:
            response.js = "jQuery('#%s').get(0).reload();" % request.vars.reload_div
            response.js += "jQuery('#table_ent').get(0).reload();"
            response.js += '$("#entity_modal").modal("hide");'
    return dict(form=form)
Just for completion, below is the code of the function to create a modal (used at main controller function). I prefer using HTML helpers in controller functions because PYTHON feels more simple to work.

def modal_helper(modal_idtitlebody_content,
                 footer_content=BUTTON('Close',
                                       **{'_type':"button",
                                          '_class':"btn btn-danger",
                                          '_data-dismiss':"modal"})):
    """ Creates a modal.

    !!!! attention: it needs to stay on first level, out of any other div or 
    container, otherwise it may not appear.
    Requires importing: BUTTON, H4, DIV from gluon.html.

    Arguments:
        modal_id (string): id of modal in page.
        title (string or web2py HMTL helper): title of the modal, display in big 
            letters on top.
        body_content (web2py HMTL helper): object to display in modal. 
            For example, a form for a table.
        footer_content (web2py HMTL helper): object to display in modal footer.
    Return:
        a DIV object of modal class.
        """
    close_btn = BUTTON(
        I(**{'_class''fa fa-times fa-2x'}),
        **{'_type':"button",
           '_class':"close",
           '_data-dismiss':"modal"})
    header_title = H4(title, _class="modal-title")
    header = DIV(header_title, close_btn, _class="modal-header")
    body = DIV(body_content, _class="modal-body")
    footer = DIV(footer_content, _class="modal-footer")
    return DIV(
        DIV(
            DIV(header, body, footer, _class="modal-content"),
            _class="modal-dialog"),
        _class="modal"_id=modal_id)

On the button to open the modal I include in request.vars the id of the component with the table of entities to make it reload after submitting the form.
The component view is simple: just make {{=form}}. Follows the main view (show_entities.html):

{{=nav_bar}}
{{=form_det}}
{{=form_ent}} 
{{=form_ret}}
<div class="widget-container-col">
    <div class="widget-box widget-color-grey">
        {{if [] == projects_list:}}
            <div class="row-12">
                <h2 class='display-5'>{{=project_name}}</h2>
            </div>
            <div class="row-12">
                {{=table_ent}}
            </div>
        {{else:}}
            {{=projects_list}}
        {{pass}}
    </div>
</div>
Important: modal must stay at first level to appear, otherwise it will inherit the z-index of its parent.
Reply all
Reply to author
Forward
0 new messages