Public
Snippet $14 authored by Owo Sugiana

Data-Driven Form

partner.py
import logging
from pyramid.view import view_config 
from pyramid.httpexceptions import HTTPFound
from deform import (
    Form,
    Button,
    ValidationFailure,
    )
import colander


PARTNER_FIELDS = [
    ('nama', 'string', 'Nama', 'required'),
    ('tempat_lahir', 'string', 'Tempat Lahir', 'required'),
    ('tgl_lahir', 'date', 'Tanggal Lahir', 'required'),
    ('nik','string', 'NIK', ''),
    ]

EMPLOYEE_FIELDS = PARTNER_FIELDS + [
    ('nip', 'string', 'NIP', 'required'),
    ]


TITLES = dict(
    customer='Pelanggan',
    employee='Karyawan')

FIELDS = dict(
    customer=PARTNER_FIELDS,
    employee=EMPLOYEE_FIELDS)

TYPES = {'string': colander.String(), 'date': colander.Date()}
MISSING = {'required': colander.required, '': colander.drop}


def schema_add(schema, field):
    name, typ, title, required = field
    colander_type = TYPES[typ]
    missing = MISSING[required]
    node = colander.SchemaNode(
            colander_type, name=name, title=title, missing=missing)
    schema.add(node)


def schema_add_fields(schema, fields):
    for field in fields:
        schema_add(schema, field)


def form_response(resp, form):
    resp['form'] = form.render()
    return resp


def insert(data):
    logging.info('data: {}'.format(data))
        

@view_config(
    route_name='partner-add', renderer='../templates/partner/add.pt')
def view_agent_add(request):
    schema = colander.Schema()
    category = request.matchdict['category']
    fields = FIELDS[category]
    schema_add_fields(schema, fields)
    btn_save = Button('save', 'Simpan')
    btn_cancel = Button('cancel', 'Batalkan')
    buttons = (btn_save, btn_cancel)
    form = Form(schema, buttons=buttons)
    title = TITLES[category]
    resp = dict(title=title)
    if not request.POST:
        return form_response(resp, form)
    items = request.POST.items()
    try:
        c = form.validate(items)
    except ValidationFailure:
        return form_response(resp, form)
    data = dict(c.items())
    insert(data)
    url = request.route_url('partner-add', category=category)
    return HTTPFound(location=url)