def convertSelect(self, valor, tipo, id): if tipo == 'list': txt = '' for i in self.decodePickle(valor): if txt: txt += ', ' + i else: txt += i return txt elif tipo == 'choice': campo = ModelsFormFields().get_Fields_byIdField(id) if campo: items = campo.list_values.splitlines() D = [] for i in items: L = i.split(' | ') if len(L) >= 2: if L[0] == valor: return L[1] return valor elif tipo == 'date': data = self.decodePickle(valor) try: return data.strftime('%d/%m/%Y') except: return '' elif tipo == 'foreign_key': campo = ModelsFormFields().get_Fields_byIdField(id) if campo: form_ref = campo.ref_form form_ref_id = form_ref.id label = form_ref.campo_label key = form_ref.campo_chave dados = ModelsFormValues().get_FormValues_byForm_and_Field( form_ref_id, key) for item in dados: if item.value == valor: dados_label = ModelsFormValues( ).get_FormValues_byForm_and_Instance_and_Field( form_ref_id, item.instance_id, label) return dados_label.value return valor
def EditFormDataBase(context, event): title = context.Title() description = context.Description() uid_form = IUUID(context) campo_chave = context.campo_chave campo_label = context.campo_label forms_id = int(context.forms_id) result = ModelsForm().get_Forns_byId(forms_id) if result: try: result.name_form = to_utf8(title) except: result.name_form = title try: result.description_form = to_utf8(description) except: result.description_form = description try: result.campo_label = to_utf8(campo_label) except: result.campo_label = campo_label try: result.campo_chave = to_utf8(campo_chave) except: result.campo_chave = campo_chave try: result.uid_form = to_utf8(uid_form) except: result.uid_form = uid_form BaseStore().store.flush() if context.active_workflow: result_fields_form = ModelsFormFields().get_Fields_ByIdForm(forms_id) for campo in campos_controle: campo['forms_id'] = int(forms_id) campo_name = campo.get('name_field') result_field = ModelsFormFields().get_Fields_ByField( campo_name, int(forms_id)) if not result_field: campo['ordenacao'] = (result_fields_form.count()) ModelsFormFields().set_FormFields(**campo)
def load_fields_form(self): form = self.request.form id_form = self.context.forms_id fields_vin = [] i = 0 fields = ModelsFormFields().get_Fields_ByIdForm(int(id_form)) camposAux = copy(fields) for item in camposAux: fields_vin.append(item.ordenacao) if fields: for field in fields: index = field.ordenacao D = {} D['name'] = field.name_field D['label'] = field.title pos = fields_vin.index(index) fields_vin.pop(pos) fields_vin.insert(pos, D) return fields_vin
def ExcludFormDataBase(context, event): basestore = BaseStore() id_form = int(context.forms_id) record_values = ModelsFormValues().get_FormValues_byForm(id_form) if record_values: for record in record_values: basestore.store.remove(record) basestore.store.flush() record_instances = ModelsFormInstance().get_Instance(id_form) if record_instances: for record in record_instances: basestore.store.remove(record) basestore.store.flush() record_parameters = ModelsParametersForm().get_ParametersForm_byFormId( id_form) if record_parameters: for record in record_parameters: basestore.store.remove(record) basestore.store.flush() record_fields = ModelsFormFields().get_Fields_ByIdForm(id_form) if record_fields: for record in record_fields: basestore.store.remove(record) basestore.store.flush() record_form = ModelsForm().get_Forns_byId(id_form) if record_form: basestore.store.remove(record_form) basestore.store.flush()
def EditFormDataBase(context, event): title = context.Title() description = context.Description() uid_form = IUUID(context) campo_chave = context.campo_chave campo_label = context.campo_label forms_id = int(context.forms_id) result = ModelsForm().get_Forns_byId(forms_id) if result: try:result.name_form = to_utf8(title) except:result.name_form = title try:result.description_form = to_utf8(description) except:result.description_form = description try:result.campo_label = to_utf8(campo_label) except:result.campo_label = campo_label try:result.campo_chave = to_utf8(campo_chave) except:result.campo_chave = campo_chave try:result.uid_form = to_utf8(uid_form) except:result.uid_form = uid_form BaseStore().store.flush() if context.active_workflow: result_fields_form = ModelsFormFields().get_Fields_ByIdForm(forms_id) for campo in campos_controle: campo['forms_id'] = int(forms_id) campo_name = campo.get('name_field') result_field = ModelsFormFields().get_Fields_ByField(campo_name, int(forms_id)) if not result_field: campo['ordenacao'] = (result_fields_form.count()) ModelsFormFields().set_FormFields(**campo)
def get_values_filter(self): filter = ModelsFormFields().get_Fields_ByField(self.context.campo_filtro, int(self.context.forms_id)) if filter: self.filter = [filter.title, filter.name_field] if self.filter: result = ModelsFormValues().get_FormValues_byForm_and_Field(int(self.context.forms_id),self.filter[1]) if result.count() > 0: L = [] for i in result: if i.value not in L: L.append(i.value) return L
def __call__(self, context): terms = [] #terms.append(SimpleTerm('', '--NOVALUE--', _(u'option_category', default=u'Padrão'))) try: id_form = int(context.forms_id) except: id_form = 0 if id_form: fields = ModelsFormFields().get_Fields_ByIdForm(id_form) for campo in fields: if campo.flag_ativo: terms.append(SimpleTerm(campo.name_field, campo.name_field, _(u'option_category', default=campo.title))) return SimpleVocabulary(terms)
def check_exclud_fields(self): id_form = int(self.context.forms_id) id_fields = int(self.request.form.get('id_fields', '0')) field = ModelsFormFields().get_Fields_byIdField(id_fields) if field: check = ModelsFormValues().get_FormValues_byForm_and_Field( id_form, field.name_field) if check: return False else: if field.ref_mult.count(): return False else: return True return True
def update(self): form = self.request.form instance = 0 formulario = form.get('form', '0') field = form.get('field', '') self.name_field = field value = form.get('value', '') self.formulario = formulario self.campos = ModelsFormFields().get_Fields_ByIdForm(int(formulario)) campo_busca = ModelsFormValues().store.find( ModelsFormValues, ModelsFormValues.fields == unicode(field), ModelsFormValues.forms_id == int(formulario), ModelsFormValues.value == unicode(value)) if campo_busca.count(): instance = campo_busca[0].instance_id self.valores = ModelsFormValues().get_FormValues_byForm_and_Instance( int(formulario), instance)
def getDadosContent(self,**kwargs): id_form = int(self.forms_id) fields = ModelsFormFields().get_Fields_ByIdForm(id_form) values = ModelsForm().get_FormValues(id_form) tools = BaseFunc() L = [] for item in values: D = {} for campo in fields: if campo.flag_ativo: data = item.find(fields=campo.name_field).one() if data: if campo.type_fields == u'bool': valor = eval(data.value) if campo.type_fields == u'date': valor = tools.decodePickle(data.value) elif data.value: valor = data.value else: valor = data.value_blob else: valor = '' D[campo.name_field] = valor append = True for arg in kwargs: if D.get(arg) not in kwargs.get(arg) and kwargs.get(arg): append = False if append: L.append(D) return L
def createEvent(self, form): obj_path = form.get('obj_path') hours_selected = form.get('hours-selected') if hours_selected and obj_path: pc = getToolByName(self.context, 'portal_catalog') obj = pc(portal_type='vindula.reservacorporativa.content.reserve', path=obj_path) if obj: folder = obj[0].getObject() if not folder.mult_horarios and len(hours_selected) > 1: self.context.plone_utils.addPortalMessage( 'Você não pode agendar mais de um horário para esta reserva.', 'error') self.request.response.redirect( folder.aq_parent.absolute_url() + '/reservation-request') return username = self.context.portal_membership.getAuthenticatedMember( ).getUserName() if form.get('name'): name = form.get('name') else: name = username title = folder.title + ' - ' + name hours_selected = self.getHoursSelected(hours_selected) for hour_selected in hours_selected: if hour_selected: date = datetime.datetime.strptime( hour_selected['date'], '%d-%m-%Y') start = hour_selected['start'] end = hour_selected['end'] id = username + '-' + date.strftime('%d-%m-%Y') + ( start + end).replace(':', '') if form.get('recurrent', False): form['recurrent'] = True else: form['recurrent'] = False if form.get('end_date', False): end_date = form.get('end_date', '') if not isinstance(end_date, DateTime): try: end_date = end_date.split('/') form['end_date'] = DateTime( int(end_date[2]), int(end_date[1]), int(end_date[0])) except: form['end_date'] = None if folder.additional_items: txt = '' for item in folder.additional_items: txt += '%s: %s \n' % (item.get( 'label', ''), form.get(item.get( 'name', ''))) form['text'] = txt self.context.createObj(folder, id, title, date.strftime('%m-%d-%Y'), start, end, form) self.context.publishObj(folder[id]) msg = createMsgEmailReserve(folder[id], 'criada') if folder[id].contact_email(): send_email( self.context, msg, 'Reserva Corporativa: ' + folder.Title(), folder[id].contact_email()) if folder.contact: send_email( self.context, msg, 'Reserva Corporativa: ' + folder.Title(), folder.contact) # TO DO: VERIFICAR NOVAMENTE SE O SLOT ESTA DISPONIVEL if form.get('edit_event'): id_old = form.get('edit_event') self.context.removeObj(folder, id_old) msg = createMsgEmailReserve(folder[id], 'alterada') send_email(self.context, msg, 'Reserva Corporativa: ' + folder.Title(), folder[id].contact_email()) self.context.plone_utils.addPortalMessage( 'Sua reserva foi alterada com sucesso.', 'info') self.request.response.redirect(self.context.portal_url() + '/my-reservations') return self.context.plone_utils.addPortalMessage( 'Sua reserva foi criada com sucesso.', 'info') self.request.response.redirect(self.context.portal_url() + '/my-reservations') #processa contentcore if folder.obj_contentcore: from vindula.contentcore.models.fields import ModelsFormFields from vindula.contentcore.registration import RegistrationLoadForm obj = folder.obj_contentcore.to_object models_fields = ModelsFormFields().get_Fields_ByIdForm( obj.forms_id) # models_fields = fields.find(ModelsFormFields.name_field.is_in(self.back_list)) self.request.form['id_event'] = '%s-%s' % (username, folder.Title()) self.request.form["form.submited"] = True tmp_obj = CustomView(obj, self.request) RegistrationLoadForm().registration_processes( tmp_obj, models_fields=models_fields, isForm=False) else: self.context.plone_utils.addPortalMessage( 'Ocorreu um erro durante a crição da sua reserva.', 'error') self.request.response.redirect(folder.aq_parent.absolute_url())
def valida_form(ctx, configuracao, form): # metodo que valida um sequencia de campos e retorna um dicionario # com os valores, erros e mensagem de erro errors = {} # dicionario que vai retornar os erros para o formulario convertidos = {} # dicionario que vai retornar os dados convertidos para unicode # var 'campo' - usado para verificar se campo e obrigatorio # var 'valor' - usado para converter dos dados inseridos no fomulario for campo in configuracao.keys(): if not 'outros_hidden' in campo: valor = form.get(campo, u'') #configuracao[campo]['campo_form'], '') # logica para verificacao de obrigatoriedade de campo if configuracao.get(campo).get('required', None) is not None: if configuracao[campo]['required'] == True: # configuracao: campo e obrigatorio if configuracao[campo]['type'] != 'bool' and\ configuracao[campo]['type'] != 'img' and\ configuracao[campo]['type'] != 'file' and\ configuracao[campo]['type'] != 'list' and\ not configuracao[campo].get('flag_multi'): if valor == '' or valor.isspace(): # se o campo estiver vazio errors[campo] = u'Este campo é obrigatório' # indica o campo vazio elif configuracao[campo].get('flag_multi'): id_form = int(ctx.context.forms_id) ref = ModelsFormFields().get_fields_byIdForm_and_RefField(id_form,campo) for i in ref: valor_tmp = form.get(i.name_field, u'') if not valor_tmp or valor_tmp.isspace(): errors[campo] = u'Este campo é obrigatório' else: if not valor: errors[campo] = u'Este campo é obrigatório' # indica o campo vazio if configuracao[campo]['type'] == date or\ configuracao[campo]['type'] == 'date' : if valor != '': try: if valor.find('/') != -1: data = valor.split('/') # pega a string no formato '00/00/0000' e transforma em tupla dividindo os elementos # separa o ano, mes e dia da tupla ano = int(data[2]) mes = int(data[1]) dia = int(data[0]) if ano < 1900: errors[campo] = u'Data inválida.' else: try: valor_convert = pickle.dumps(date(ano, mes, dia)) convertidos[campo] = to_utf8(valor_convert) except: errors[campo] = u'Data inválida.' else: data_hora = valor.split(' ') # pega a string no formato '0000-00-00 00:00' e transforma em tupla dividindo os elementos data = data_hora[0].split('-') # separa o ano, mes e dia da tupla ano = int(data[0]) mes = int(data[1]) dia = int(data[2]) if ano < 1900: errors[campo] = u'Data inválida.' else: try: valor_convert = pickle.dumps(date(ano, mes, dia)) convertidos[campo] = to_utf8(valor_convert) except: errors[campo] = u'Data inválida.' except: errors[campo] = u'Data inválida.' #logica para converter campos tipo Boolen elif configuracao[campo]['type'] == 'bool': if valor: convertidos[campo] = True else: convertidos[campo] = False #logica para converter campos tipo Boolen elif configuracao[campo]['type'] == bool: if valor: convertidos[campo] = True else: convertidos[campo] = False elif configuracao[campo]['type'] == int: convertidos[campo] = int(valor) elif configuracao[campo]['type'] == 'choice': if type(valor) == unicode: convertidos[campo] = valor.strip() else: convertidos[campo] = to_utf8(valor.strip()) elif configuracao[campo]['type'] == 'radio': if type(valor) == unicode: convertidos[campo] = valor.strip() else: convertidos[campo] = to_utf8(valor.strip()) elif configuracao[campo]['type'] == 'combo': um = valor[0] dois = valor[1] if um != '' and dois != '': errors[campo] = u'Preencha somente um campo' else: if um != '': convertidos[campo] = to_utf8(um) elif dois != '': convertidos[campo] = to_utf8(dois) elif configuracao[campo]['type'] == 'hidden': try: convertidos[campo] = int(valor) except: convertidos[campo] = to_utf8(valor.strip()) elif configuracao[campo]['type'] == 'text': if type(valor) == unicode: convertidos[campo] = valor.strip() else: convertidos[campo] = to_utf8(valor.strip()) elif configuracao[campo]['type'] == 'list': valor_convert = '' if type(valor) == list: valor_convert = pickle.dumps(valor) convertidos[campo] = to_utf8(valor_convert) else: L = [] L.append(valor) valor_convert = pickle.dumps(L) convertidos[campo] = to_utf8(valor_convert) elif configuracao[campo]['type'] == 'img': data = valor.read() filename = valor.filename if configuracao[campo]['required'] == True and len(data) == 0: errors[campo] = u'Este campo é obrigatório' # indica o campo vazio else: if len(data) != 0 : # Adicionado dicionario na versão 1.1 do vindula D ={} D['data'] = data D['filename'] = filename valor_convert = pickle.dumps(D) convertidos[campo] = to_utf8(valor_convert) else: convertidos[campo] = '' #logica para converter campos tipo File elif configuracao[campo]['type'] == 'file': if isinstance(valor, str): valor = pickle.loads(valor) data = valor.get('data', '') filename = valor.get('filename', '') else: data = valor.read() filename = valor.filename if configuracao[campo]['required'] == True and len(data) == 0: errors[campo] = u'Este campo é obrigatório' # indica o campo vazio else: if len(data) != 0 : D ={} D['data'] = data D['filename'] = filename valor_convert = pickle.dumps(D) convertidos[campo] = to_utf8(valor_convert) else: convertidos[campo] = '' elif configuracao[campo]['type'] == 'textarea': if type(valor) == unicode: convertidos[campo] = valor.strip() else: convertidos[campo] = to_utf8(valor.strip()) elif configuracao[campo]['type'] == 'key': normalizer = getUtility(IIDNormalizer) convertidos[campo] = to_utf8(normalizer.normalize(unicode(valor, 'utf-8'))) elif configuracao[campo]['type'] == 'email': if(re.match('(.+)@(.+)\.(.+)',valor,re.IGNORECASE)): if type(valor) == unicode: convertidos[campo] = valor.strip() else: convertidos[campo] = to_utf8(valor.strip()) else: errors[campo] = u'E mail inválido, digite um email valido' # logica para conversao de dados para unicode de acordo com a configuracao elif valor != '' and valor != '--NOVALUE--' and valor != '-- Selecione --': # se o campo nao estiver vazio, vai tentar converter if campo != 'skills_expertise' and campo != 'languages': try: if type(valor) == unicode: convertidos[campo] = valor.strip() else: convertidos[campo] = to_utf8(valor.strip()) # conversao do campo # "(valor)" == "(def __call__(self, *args, **kwargs):", callable except: # Falhou ao converter para o tipo requerido errors[campo] = u'Erro ao converter o conteúdo do campo para um formato válido' #errors[campo] = u'Não foi possível converter o campo %s para %s.' % (campo, configuracao[campo]['type']) return errors, convertidos #retorna campos validados
def get_field(self): field = self.fields form = self.forms_id return ModelsFormFields().get_Fields_ByField(field, form)
def update(self): filename = str(self.context.id) + '-export-register.xls' id_form = int(self.context.forms_id) fields = ModelsFormFields().get_Fields_ByIdForm(int(id_form)) types = ['img', 'file'] form = self.request.form campos_vin = [] values = ModelsForm().get_FormValues(id_form) L = [] for item in values: if self.checkItem(item, form): L.append(item) values = L if fields: fields = fields.find(flag_ativo=True) # Create Excel workbook wb = xl.Workbook() # Create Excel sheet and header mysheet = wb.add_sheet(self.context.Title() or self.context.id) #Nome do sheet #write headers header_font = xl.Font() #make a font object header_font.bold = True header_font.underline = True #font needs to be style actually header_style = xl.XFStyle() header_style.font = header_font for field in fields: titulo = field.title.replace(';', ',') if isinstance(titulo, str): titulo = titulo.decode('utf-8') campos_vin.append(titulo.decode('utf-8')) for col, value in enumerate(campos_vin): mysheet.write(0, col, value, header_style) if values: for row_num, row_value in enumerate(values): row_num += 1 #start at row 1 for col, field in enumerate(fields): #Campos de histórico if field.name_field in [ 'observacao_responsavel', 'my_observacao' ]: data = row_value.find(fields=field.name_field) valor = '' if data and data.count(): data = data[0] log_data = data.get_logField() if log_data and log_data.count(): for log in log_data: valor += str(log.valor_new).replace( '\n', '').replace('\r', '').replace(';', ',') valor += ' \\ ' else: data = row_value.find( fields=field.name_field).one() if not field.type_fields in types and data: if field.type_fields == 'list': valor = '' for i in self.decodePickle(data.value): valor += i + ',' elif field.type_fields == 'date': campo_data = self.decodePickle(data.value) valor = campo_data.strftime('%d/%m/%Y') else: valor = str(data.value).replace( '\n', '').replace('\r', '').replace(';', ',') else: valor = '' if isinstance(valor, str): valor = valor.decode('utf-8') mysheet.write(row_num, col, valor) # Write out Excel file wb.save(filename) self.request.response.setHeader( 'Content-Type', 'application/x-excel; charset=utf-8') self.request.response.setHeader( 'Content-Disposition', 'attachment; filename=%s' % (filename)) self.request.response.write(file(filename, "r").read())
def CreatFormDataBase(context, event): title = context.Title() description = context.Description() uid_form = IUUID(context) forms_id = context.forms_id D = {} try: D['name_form'] = to_utf8(title) except: D['name_form'] = title try: D['description_form'] = to_utf8(description) except: D['description_form'] = description try: D['uid_form'] = to_utf8(uid_form) except: D['uid_form'] = uid_form id_form = ModelsForm().set_Form(**D) if forms_id != id_form: context.forms_id = id_form if context.active_workflow: for campo in campos_controle: campo['forms_id'] = int(id_form) ModelsFormFields().set_FormFields(**campo) if 'original' in event.__dict__.keys(): org = event.original new = event.object fields_org = ModelsFormFields().get_Fields_ByIdForm(int(org.forms_id)) campos = ['name_field','type_fields', 'list_values','title','value_default',\ 'description_fields','ordenacao','required','flag_ativo', 'flag_float_left'] for item in fields_org: D = {} for i in campos: D[i] = item.__getattribute__(i) D['forms_id'] = int(new.forms_id) ModelsFormFields().set_FormFields(**D) instances_org = ModelsFormInstance().get_Instance(int(org.forms_id)) for instance in instances_org: values_instance = ModelsFormValues( ).get_FormValues_byForm_and_Instance(int(org.forms_id), instance.instance_id) id_inst = ModelsFormInstance().set_FormInstance(int(new.forms_id)) campos_value = ['value', 'value_blob', 'fields'] for value in values_instance: D = {} for i in campos_value: D[i] = value.__getattribute__(i) D['forms_id'] = int(new.forms_id) D['instance_id'] = id_inst ModelsFormValues().set_FormValues(**D)
def get_Form_fields(self): id_form = int(self.context.forms_id) return ModelsFormFields().get_Fields_ByIdForm(id_form)
def geraCampos(self, form_data): if type(form_data) == dict: errors = form_data.get('errors', None) data = form_data.get('data', None) campos = form_data.get('campos', None) value_choice = form_data.get('lista_itens', {}) default_value = form_data.get('default_value', {}) html = [] # i=0 # while i < len(campos.keys()): # html.append(i) # i+=1 #Ordenando os campos pela chave 'ordem' campos = OrderedDict((sorted(campos.items(), key=lambda campo: campo[1]['ordem']))) for campo in campos.keys(): # index = campos[campo].get('ordem',0) tmp = "" valor = '' obj_campo = campos[campo].get('obj', '') if not 'outros_hidden' in campo: type_campo = campos[campo].get('type', '') if type_campo == 'richtext': classe = 'richTextWidget' elif type_campo == 'referencia': tmp += '' # html.pop(index) # html.insert(index, tmp) # html.append(tmp) continue else: classe = '' mascara_campo = campos[campo].get('mascara', None) if mascara_campo: mascara = "onKeyDown='Mascara(this,{0});' onKeyPress='Mascara(this,{0});' onKeyUp='Mascara(this,{0});'".format( mascara_campo) else: mascara = '' #Classe para campo oculto if type_campo == 'hidden': classe += ' hidden_field' #Campo Com Float Left if campos[campo].get('flag_float_left', False): classe += ' left' tmp += "<!-- Campo %s -->" % (campo) tmp += "<div class='%s' id='%s'>" % (self.field_class( errors, campo) + ' ' + classe, 'field-' + campo) if type_campo != 'hidden' and type_campo != 'bool': tmp += " <label for='%s'>%s</label>" % ( campo, campos[campo].get('label', '')) tmp += " <div class='formHelp'>%s</div>" % ( campos[campo].get('decription', '')) if campos[campo].get( 'required', '') == True and type_campo != 'hidden': tmp += " <span class='fieldRequired' title='Obrigatório'> </span>" tmp += " <div >%s</div>" % (errors.get(campo, '')) if type_campo == 'hidden': valor += "<input id='%s' type='hidden' value='%s' name='%s' size='25'/>" % ( campo, self.getValue(campo, self.request, data, default_value), campo) elif type_campo == 'img': if errors: if self.getPhoto(campo, self.request, data): valor += "<img src='%s' style='width:100px;height:100px;' /><br />" % ( self.getPhoto(campo, self.request, data)) else: if self.getPhoto(campo, self.request, data): valor += "<img src='%s' style='width:100px;height:100px;' /><br />" % ( self.getPhoto(campo, self.request, data)) valor += "<input id='%s' type='file' value='%s' name='%s' size='25' />" % ( campo, self.getPhoto(campo, self.request, data), campo) elif type_campo == 'file': if errors: if self.getFile(campo, self.request, data): valor += "<a href='%s' target='_blank'>Download do Arquivo</a><br />" % ( self.getFile(campo, self.request, data)) else: if self.getFile(campo, self.request, data): valor += "<a href='%s' target='_blank'>Download do Arquivo</a><br />" % ( self.getFile(campo, self.request, data)) valor += "<input id='%s' type='file' value='%s' name='%s' size='25' />" % ( campo, self.getFile(campo, self.request, data), campo) elif type_campo == 'date': valor += """<input id='%s' type='text' maxlength='10' class="dateField" value='%s' name='%s' size='25'/>""" % ( campo, self.converte_data( self.getValuePickle(campo, self.request, data, default_value), True), campo) elif type_campo == 'textarea': valor += "<textarea id='%s' name='%s' style='width: 100; height: 81px;'>%s</textarea>" % ( campo, campo, self.getValue(campo, self.request, data, default_value)) elif type_campo == 'bool': valor += "<input id='%s' type='checkbox' value='%s' name='%s' size='25' %s/>" % ( campo, 'True', campo, self.checked(campo, self.request, data, default_value)) elif type_campo == 'combo': select = False valor += "<select name='%s'>" % (campo) valor += "<option value=" ">-- Selecione --</option>" for item in value_choice[campo]: if item[0] == self.getValue( campo, self.request, data, default_value): select = True valor += "<option value='%s' selected>%s</option>" % ( item[0], item[-1]) else: valor += "<option value='%s'>%s</option>" % ( item[0], item[-1]) valor += "</select>" if select: valor += "<input id='%s' type='text' value='%s' name='%s' size='25'/>" % ( campo, '', campo) else: valor += "<input id='%s' type='text' value='%s' name='%s' size='25'/>" % ( campo, self.getValue(campo, self.request, data, default_value), campo) elif type_campo == 'list': valor += "<div class='boxSelecao' name='%s'>" % (campo) for item in value_choice[campo]: lable = item[0] if item[0] in self.getValueList( campo, self.request, data, default_value): valor += "<input value='%s' type='checkbox' checked name='%s'/><span>%s</span><br/>" % ( item[0], campo, lable) else: valor += "<input value='%s' type='checkbox' name='%s'/><span>%s</span><br/>" % ( item[0], campo, lable) valor += "</div>" elif type_campo == 'choice': valor += "<select name='%s'>" % (campo) valor += "<option value=" ">-- Selecione --</option>" for item in value_choice[campo]: if item[0] == self.getValue( campo, self.request, data, default_value): valor += "<option value='%s' selected>%s</option>" % ( item[0], item[-1]) else: valor += "<option value='%s'>%s</option>" % ( item[0], item[-1]) valor += "</select>" elif type_campo == 'radio': valor += "<div id='%s' >" % (campo) for item in value_choice[campo]: if item[0] == self.getValue( campo, self.request, data, default_value): valor += "<input type='radio' name='%s' value='%s' checked >%s" % ( campo, item[0], item[-1]) else: valor += "<input type='radio' name='%s' value='%s' >%s" % ( campo, item[0], item[-1]) valor += '<br />' valor += "</div>" elif type_campo == 'foreign_key': refform = obj_campo.ref_form valor += "<select name='%s' class='select-filter' data-ref_from='%s' data-id_field='%s' >" % ( campo, refform.id, refform.campo_chave) valor += "<option value=" ">-- Selecione --</option>" for item in value_choice[campo]: if item[0] == self.getValue( campo, self.request, data, default_value): valor += "<option value='%s' selected>%s</option>" % ( item[0], item[-1]) else: valor += "<option value='%s'>%s</option>" % ( item[0], item[-1]) valor += "</select>" valor += '<div id="ajax_content_%s"> </div>' % (campo) elif type_campo == 'richtext': url = self.context.absolute_url() valor += "<div class='fieldTextFormat'><label>Formato do Texto</label>" valor += "<select name='%s_text_format' id='%s_text_format'><option value='text/html' selected='selected'>HTML</option>" % ( campo, campo) valor += "<option value='text/x-web-textile'>Textile</option><option value='text/x-plone-outputfilters-html'>Plone Output Filters HTML</option></select></div>" valor += "<input class='cke_config_ur' type='hidden' value='%s/ckeditor_plone_config.js' name='cke_config_url'>" % ( url) valor += "<input class='cke_iswidget' type='hidden' value='True' name='cke_iswidget'>" valor += "<div class='widget_settings'><input class='cke_baseHref' type='hidden' name='cke_baseHref' value='%s' >" % ( url) valor += "<input class='cke_height' type='hidden' value='100px' name='cke_height'></div>" valor += "<textarea id='%s' class='ckeditor_plone' name='%s' rows='25' cols='40' >%s</textarea>" % ( campo, campo, self.getValue(campo, self.request, data, default_value)) # utility = getUtility(ITinyMCE) # conf = utility.getConfiguration(context=self.context, # field=campo, # request=self.request) # # valor += "<div class='fieldTextFormat'><label>Formato do Texto</label>" # valor += "<select name='%s_text_format' id='%s_text_format'><option value='text/html' selected='selected'>HTML</option>"%(campo,campo) # valor += "<option value='text/x-web-textile'>Textile</option><option value='text/x-plone-outputfilters-html'>Plone Output Filters HTML</option></select></div>" # valor += "<textarea id='%s' class='mce_editable' name='%s' rows='25' cols='40' title='%s' >%s</textarea>"%(campo,campo, conf, self.getValue(campo, self.request,data, default_value)) elif type_campo != 'referencia': valor += "<input id='%s' type='text' value='%s' name='%s' size='25' %s />" % ( campo, self.getValue(campo, self.request, data, default_value), campo, mascara) if campos[campo].get('flag_multi'): table = '' table += '<table id="listing-table" class="listing"><th style="width: 50%"></th>' if type_campo in ['list', 'radio']: for item in value_choice[campo]: table += '<th class="posted">%s</th>' % ( item[-1]) else: table += '<th>%s</th>' % ('Responda') id_form = int(self.context.forms_id) ref = ModelsFormFields( ).get_fields_byIdForm_and_RefField(id_form, campo) for i in ref: mascara_campo = i.mascara or '' if mascara_campo: mascara = "onKeyDown='Mascara(this,{0});' onKeyPress='Mascara(this,{0});' onKeyUp='Mascara(this,{0});'".format( mascara_campo) else: mascara = '' table += '<tr><td>%s</td>' % (i.title) valor = '' if type_campo == 'list': for item in value_choice[campo]: valor = '' lable = item[-1] if item[0] in self.getValueList( i.name_field, self.request, data, default_value): valor += "<input value='%s' type='checkbox' checked name='%s'/>" % ( item[0], i.name_field) else: valor += "<input value='%s' type='checkbox' name='%s'/>" % ( item[0], i.name_field) table += '<td>%s</td>' % (valor) elif type_campo == 'radio': for item in value_choice[campo]: valor = '' if item[0] == self.getValue( i.name_field, self.request, data, default_value): valor += "<input type='radio' name='%s' value='%s' checked >" % ( i.name_field, item[0]) else: valor += "<input type='radio' name='%s' value='%s' >" % ( i.name_field, item[0]) table += '<td>%s</td>' % (valor) elif type_campo == 'img': if errors: if self.getPhoto(i.name_field, self.request, data): valor += "<img src='%s' style='width:100px;height:100px;' /><br />" % ( self.getPhoto( campo, self.request, data)) else: if self.getPhoto(i.name_field, self.request, data): valor += "<img src='%s' style='width:100px;height:100px;' /><br />" % ( self.getPhoto( i.name_field, self.request, data)) valor += "<input id='%s' type='file' value='%s' name='%s' size='25' />" % ( i.name_field, self.getPhoto(i.name_field, self.request, data), i.name_field) table += '<td>%s</td>' % (valor) elif type_campo == 'file': if errors: if self.getFile(i.name_field, self.request, data): valor += "<a href='%s' target='_blank'>Download do Arquivo</a><br />" % ( self.getFile( i.name_field, self.request, data)) else: if self.getFile(i.name_field, self.request, data): valor += "<a href='%s' target='_blank'>Download do Arquivo</a><br />" % ( self.getFile( i.name_field, self.request, data)) valor += "<input id='%s' type='file' value='%s' name='%s' size='25' />" % ( campo, self.getFile(i.name_field, self.request, data), campo) table += '<td>%s</td>' % (valor) elif type_campo == 'date': valor += """<input id='%s' type='text' maxlength='10' onKeyDown='Mascara(this,Data);' onKeyPress='Mascara(this,Data);' onKeyUp='Mascara(this,Data);' value='%s' name='%s' size='25'/>""" % ( i.name_field, self.converte_data( self.getValuePickle( i.name_field, self.request, data, default_value), True), i.name_field) table += '<td>%s</td>' % (valor) elif type_campo == 'textarea': valor += "<textarea id='%s' name='%s' style='width: 100; height: 81px;'>%s</textarea>" % ( i.name_field, i.name_field, self.getValue(i.name_field, self.request, data, default_value)) table += '<td>%s</td>' % (valor) elif type_campo == 'bool': valor += "<input id='%s' type='checkbox' value='%s' name='%s' size='25' %s/>" % ( i.name_field, 'True', i.name_field, self.checked(i.name_field, self.request, data, default_value)) tmp += " <label class='label-input' for='%s'>%s</label>" % ( campo, campos[campo].get('label', '')) tmp += " <div class='formHelp'>%s</div>" % ( campos[campo].get('decription', '')) table += '<td>%s</td>' % (valor) elif type_campo == 'choice': valor += "<select name='%s'>" % (i.name_field) valor += "<option value=" ">-- Selecione --</option>" for item in value_choice[campo]: if item[0] == self.getValue( i.name_field, self.request, data, default_value): valor += "<option value='%s' selected>%s</option>" % ( item[0], item[-1]) else: valor += "<option value='%s'>%s</option>" % ( item[0], item[-1]) valor += "</select>" table += '<td>%s</td>' % (valor) elif type_campo != 'referencia': valor += "<input id='%s' type='text' value='%s' name='%s' size='25' %s />" % ( i.name_field, self.getValue( i.name_field, self.request, data, default_value), i.name_field, mascara) table += '<td>%s</td>' % (valor) table += '</tr>' table += '</table>' tmp += table + "</div>" else: tmp += valor + "</div>" if type_campo != 'hidden' and type_campo == 'bool': tmp += " <label class='label-input' for='%s'>%s</label>" % ( campo, campos[campo].get('label', '')) tmp += " <div class='formHelp'>%s</div>" % ( campos[campo].get('decription', '')) tmp += " <div >%s</div>" % (errors.get(campo, '')) else: tmp += '' # html.pop(index) # html.insert(index, tmp) html.append(tmp) return html
def get_Form_fields(self, id_form): return ModelsFormFields().get_Fields_ByIdForm(int(id_form))
def geraHTMLContent(self, id, tipo, valor, full_text=False): if tipo == 'list': txt = '' for i in self.decodePickle(valor): txt += i + ', ' return txt elif tipo == 'img': if id: return '<img width="100px" src="../form-image?id=%s">' % id else: return '' elif tipo == 'file': if id: arquivo = self.decodePickle(valor) if arquivo != '': name = arquivo.get('filename', '') return '<a href="../form-file?id=%s" target="_blank">%s</a><br />' % ( id, name) else: return '' else: return '' elif tipo == 'date': data = self.decodePickle(valor) try: return data.strftime('%d/%m/%Y') except: return '' elif tipo == 'choice': if id: valor_campo = ModelsFormValues().get_Values_byID(id) id_form = int(self.context.forms_id) if valor_campo: campo = ModelsFormFields().get_Fields_ByField( valor_campo.fields, id_form) items = campo.list_values.splitlines() D = [] for i in items: L = i.split(' | ') if len(L) >= 2: if L[0] == valor: return L[1] return valor elif tipo == 'foreign_key': if id: valor_campo = ModelsFormValues().get_Values_byID(id) id_form = int(self.context.forms_id) if valor_campo: campo = ModelsFormFields().get_Fields_ByField( valor_campo.fields, id_form) if campo: form_ref = campo.ref_form form_ref_id = form_ref.id label = form_ref.campo_label key = form_ref.campo_chave if full_text: instance = 0 txt = '' v_campos = form_ref.fields campo_busca = ModelsFormValues().store.find( ModelsFormValues, ModelsFormValues.fields == key, ModelsFormValues.forms_id == form_ref_id, ModelsFormValues.value == valor) if campo_busca.count(): instance = campo_busca[0].instance_id valores = ModelsFormValues( ).get_FormValues_byForm_and_Instance( form_ref_id, instance) txt = '<br/>' for v_campo in v_campos: v_valor = valores.find( fields=v_campo.name_field).one() txt += '<b> %s : </b><span> %s </span><br/>' % ( v_campo.title, v_valor.value) return txt else: dados = ModelsFormValues( ).get_FormValues_byForm_and_Field( form_ref_id, key) for item in dados: if item.value == valor: dados_label = ModelsFormValues( ).get_FormValues_byForm_and_Instance_and_Field( form_ref_id, item.instance_id, label) return dados_label.value return valor
def get_Form_fields(self): #form = self.request.form id_form = int(self.context.forms_id) if id_form: # 'forms_id' in form.keys(): return ModelsFormFields().get_Fields_ByIdForm(int(id_form))
def get_Field(self, campo): data = ModelsFormFields().get_Fields_ByField(campo,self.form_id) return data
def update(self): filename = str(self.context.id)+'-export-register.xls' id_form = int(self.context.forms_id) fields = ModelsFormFields().get_Fields_ByIdForm(int(id_form)) types = ['img','file'] form = self.request.form campos_vin = [] values = ModelsForm().get_FormValues(id_form) L = [] for item in values: if self.checkItem(item, form): L.append(item) values = L if fields: fields = fields.find(flag_ativo=True) # Create Excel workbook wb = xl.Workbook() # Create Excel sheet and header mysheet = wb.add_sheet(self.context.Title() or self.context.id) #Nome do sheet #write headers header_font=xl.Font() #make a font object header_font.bold=True header_font.underline=True #font needs to be style actually header_style = xl.XFStyle(); header_style.font = header_font for field in fields: titulo = field.title.replace(';', ',') if isinstance(titulo, str): titulo = titulo.decode('utf-8') campos_vin.append(titulo.decode('utf-8')) for col,value in enumerate(campos_vin): mysheet.write(0,col,value,header_style) if values: for row_num,row_value in enumerate(values): row_num+=1 #start at row 1 for col, field in enumerate(fields): #Campos de histórico if field.name_field in ['observacao_responsavel', 'my_observacao']: data = row_value.find(fields=field.name_field) valor = '' if data and data.count(): data = data[0] log_data = data.get_logField() if log_data and log_data.count(): for log in log_data: valor += str(log.valor_new).replace('\n', '').replace('\r', '').replace(';', ',') valor += ' \\ ' else: data = row_value.find(fields=field.name_field).one() if not field.type_fields in types and data: if field.type_fields == 'list': valor = '' for i in self.decodePickle(data.value): valor += i +',' elif field.type_fields == 'date': campo_data = self.decodePickle(data.value) valor = campo_data.strftime('%d/%m/%Y') else: valor = str(data.value).replace('\n', '').replace('\r', '').replace(';', ',') else: valor = '' if isinstance(valor, str): valor = valor.decode('utf-8') mysheet.write(row_num,col,valor) # Write out Excel file wb.save(filename) self.request.response.setHeader('Content-Type', 'application/x-excel; charset=utf-8') self.request.response.setHeader('Content-Disposition','attachment; filename=%s'%(filename)) self.request.response.write(file(filename,"r").read())
def get_fields(self): return ModelsFormFields().get_Fields_ByIdForm(self.form_id)