自定义字段样式

在日常开发中,我们经常会遇到需要根据业务规则动态展示字段样式的场景,比如表格、表单或详情中的某些字段需要改变文字颜色。本文将通过一个具体的案例,带大家实现这一功能。

以下以 自定义表格字段文字颜色 为例。


实现步骤

1. 在界面设计器中添加组件

通过界面设计器,添加一个组件
自定义字段样式


2. 创建元件

以表格的「金额字段」为例,创建对应的元件(可根据自己的业务场景调整)。
自定义字段样式


3. 配置元件属性

进入元件设计页面,从组件库中拖入「单行文本」到设计区域。在右侧属性面板中填写相关配置并保存

自定义字段样式


4. 保存元件

完成配置后,保存元件。


5. 发布元件

将元件发布,供页面设计使用。


6. 切换表格字段

进入页面设计器,将表格中的字段切换为刚刚创建的元件。

自定义字段样式


7. 配置字段颜色

在右侧属性面板中,配置字段的文字颜色:

  • 固定颜色:直接输入颜色值(如 red)。
  • 动态颜色:输入表达式,根据业务逻辑动态展示颜色。例如:当前行的名称等于 1 时显示红色,否则为蓝色。

示例表达式:

activeRecord.name === '1' ? 'red' : 'blue'

自定义字段样式


8: 在代码中,自定义对应的表格字段

import {
  SPI,
  BaseFieldWidget,
  ModelFieldType,
  ViewType,
  TableCurrencyFieldWidget,
  Widget,
  RowContext,
  numberZeroFill,
  numberAddThousandth,
  Expression,
  ExpressionRunParam
} from '@kunlun/dependencies';
import { toString } from 'lodash-es';
import { createVNode, VNode } from 'vue';

@SPI.ClassFactory(
  BaseFieldWidget.Token({
    viewType: [ViewType.Table],
    ttype: [ModelFieldType.Currency],
    widget: 'TableCurrencyColor'
  })
)
export class TableCustomCurrencyFieldWidget extends TableCurrencyFieldWidget {
  computedFieldColor(context: RowContext) {
    const { fieldColor = ' ' } = this.getDsl();

    if (!fieldColor) {
      return null;
    }

    // 如果当前颜色是表达式,则需要计算
    if (Expression.hasKeywords(fieldColor)) {
      const params: ExpressionRunParam = {
        activeRecords: [context.data],
        rootRecord: {},
        openerRecord: {},
        scene: ''
      };

      return Expression.run(params, fieldColor, fieldColor)!;
    }

    return fieldColor;
  }

  @Widget.Method()
  public renderDefaultSlot(context: RowContext): VNode[] | string {
    let value = numberZeroFill(toString(super.compute(context)), this.getPrecision(context));
    if (this.getShowThousandth(context)) {
      value = numberAddThousandth(value);
    }

    return [
      createVNode(
        'div',
        {
          style: {
            color: this.computedFieldColor(context)
          }
        },
        value
      )
    ];
  }
}

9: 页面效果图

自定义字段样式

Oinone社区 作者:汤乾华原创文章,如若转载,请注明出处:https://doc.oinone.top/other/20257.html

访问Oinone官网:https://www.oinone.top获取数式Oinone低代码应用平台体验

(0)
汤乾华的头像汤乾华数式员工
上一篇 2025年1月8日 am10:30
下一篇 2025年1月9日 pm5:12

相关推荐

  • 后端脚手架生成工程

    后端脚手架生成工程 1、使用如下命令来利用项目脚手架生成工程:新建archetype-project-generate.sh(bat) 脚本 archetype-project-generate.sh #!/bin/bash # 项目生成脚手架 # 用于新项目的构建 # 脚手架使用目录 # 本地 local # 本地脚手架信息存储路径 ~/.m2/repository/archetype-catalog.xml archetypeCatalog=local # 以下参数以pamirs-demo为例 # 新项目的groupId groupId=pro.shushi.pamirs.demo # 新项目的artifactId artifactId=pamirs-demo # 新项目的version version=1.0.0-SNAPSHOT # Java包名前缀 packagePrefix=pro.shushi # Java包名后缀 packageSuffix=pamirs.demo # 新项目的pamirs platform version pamirsVersion=6.2.8 # Java类名称前缀 javaClassNamePrefix=Demo # 项目名称 module.displayName projectName=OinoneDemo # 模块 MODULE_MODULE 常量 moduleModule=demo_core # 模块 MODULE_NAME 常量 moduleName=DemoCore # spring.application.name applicationName=pamirs-demo # tomcat server address serverAddress=0.0.0.0 # tomcat server port serverPort=8090 # redis host redisHost=127.0.0.1 # redis port redisPort=6379 # 数据库名 db=demo # zookeeper connect string zkConnectString=127.0.0.1:2181 # zookeeper rootPath zkRootPath=/demo mvn archetype:generate \ -DinteractiveMode=false \ -DarchetypeCatalog=${archetypeCatalog} \ -DarchetypeGroupId=pro.shushi.pamirs.archetype \ -DarchetypeArtifactId=pamirs-project-archetype \ -DarchetypeVersion=6.2.8 \ -DgroupId=${groupId} \ -DartifactId=${artifactId} \ -Dversion=${version} \ -DpamirsVersion=${pamirsVersion} \ -Dpackage=${packagePrefix}.${packageSuffix} \ -DpackagePrefix=${packagePrefix} \ -DpackageSuffix=${packageSuffix} \ -DjavaClassNamePrefix=${javaClassNamePrefix} \ -DprojectName="${projectName}" \ -DmoduleModule=${moduleModule} \ -DmoduleName=${moduleName} \ -DapplicationName=${applicationName} \ -DserverAddress=${serverAddress} \ -DserverPort=${serverPort} \ -DredisHost=${redisHost} \ -DredisPort=${redisPort} \ -Ddb=${db} \ -DzkConnectString=${zkConnectString} \ -DzkRootPath=${zkRootPath} archetype-project-generate.bat @echo off :: 项目生成脚手架 set archetypeCatalog=local set groupId=pro.shushi.pamirs.demo set artifactId=pamirs-demo set version=1.0.0-SNAPSHOT set packagePrefix=pro.shushi set packageSuffix=pamirs.demo set pamirsVersion=6.2.8 set javaClassNamePrefix=Demo set projectName=OinoneDemo set moduleModule=demo_core set moduleName=DemoCore set applicationName=pamirs-demo set serverAddress=0.0.0.0 set serverPort=8090 set redisHost=127.0.0.1 set redisPort=6379 set db=demo set…

    2025年8月22日
    47100
  • 工作流审批退回,撤销API

    审批退回API mutation { workflowUserTaskMutation { approveRejust( workflowUserTask: {id: 701530152718787758, userTaskViewName: "工作流任务待办xml_workflow", userTaskReadonlyViewName: "工作流任务待办detail_workflow", source: "超级管理员", statusDisplayName: "待处理", avatarUrl: "https://pamirs.oss-cn-hangzhou.aliyuncs.com/oinone/img/workflow/default.png", name: "测试流程", instanceId: 701530152718787737, taskId: 701530152718787756, definitionId: 701530152718787698, definitionVersion: 34, canAddSignApproval: false, content: null, nodeId: "APPROVAL0000000000014502", userType: USER_TYPE_USER, userId: 10001, model: "top.Teacher", nodeContext: "{\"id\":\"700755598316612629\",\"teacherName\":\"1234312\",\"readStatus\":\"NO_READ\",\"pamirsUser\":[]}", taskType: APPROVE, viewId: 701530152718787696, viewReadonlyId: 701530152718787697, taskCreateDate: "2025-01-22 14:31:12", flowCreateDate: "2025-01-22 14:30:50", allowTransfer: false, allowAddSign: false, allowFallback: true, allowStaging: true, allowAgree: true, allowReject: true, readConfirm: false, mustReason: false, isUrge: false, status: ACTIVE, filterAddSign: "id>=0 ", filterTransfer: "id>=0 ", hasFallback: true, workflowBackNode: {id: 701530152718787702, fallBackNodeName: "填写"}, filterFallBackNodeIds: "'WRITE0000000000014501'"} ) { id addSignUserId transferUserId workflowBackNodeId enableCustomView isCopy isRecall isClose isFallBack operateType workflowModule { id logo bitOptions attributes displayName sys name systemSource module sign abbr hash dsKey summary description state boot application latestVersion platformVersion publishedVersion publishCount defaultCategory category moduleDependencies moduleExclusions moduleUpstreams excludeHooks priority website author demo web license toBuy maintainer contributors url selfBuilt metaSource clientTypes show defaultHomePageModel homePageModel defaultHomePageName homePageName defaultLogo createDate writeDate createUid writeUid } module userTaskViewName userTaskReadonlyViewName source fromDepartment fromCorpName fromCorpLogo fromCorpId workflowVersion statusDisplayName helpDisplayName avatarUrl name title workflowUserInstanceId instanceId instance { id name title bizType source fromDepartment…

    2025年1月22日
    97500
  • 打印支持非存储数据导出

    介绍 平台提供的默认打印功能没有支持非存储数据的导出。我们可以自定义打印导出功能,以满足业务中个性化的需求。 实现思路 重写打印任务模型,添加业务数据字段 自定义打印动作,前端将导出数据放到业务数据字段中 使用导出数据扩展点机制修改导出数据 代码示例 继承平台的打印任务模型,加上需要业务数据字段,这个字段用于传输需要打印的表单数据,但是需要自定义打印的表单往往不止一个,所以需要定义为通用的Object字段。 @Model.model(TransientPdfPrintTask.MODEL_MODEL) @Model(displayName = "传输模型Pdf打印任务") public class TransientPdfPrintTask extends PdfPrintTask { public static final String MODEL_MODEL="demo.TransientPdfPrintTask"; @Field(displayName = "业务数据") private Object businessData; } 自定义打印动作 @Model.model(TransientPdfPrintTask.MODEL_MODEL) @Component public class TransientPdfPrintTaskAction extends AbstractPdfPrintTaskAction<TransientPdfPrintTask> { @Resource private PdfFileService pdfFileService; @Action(displayName = "打印", contextType = ActionContextTypeEnum.CONTEXT_FREE, bindingType = {ViewTypeEnum.TABLE}) @Override public TransientPdfPrintTask createPrintTask(TransientPdfPrintTask data) { return super.createPrintTask(data); } @Override protected void doExport(TransientPdfPrintTask exportTask, PdfDefinitionContext context) { pdfFileService.doExportSync(exportTask, context); } @Function.Advanced(type = FunctionTypeEnum.QUERY) @Function(openLevel = FunctionOpenEnum.API) public TransientPdfPrintTask construct(TransientPdfPrintTask data) { String model = FetchUtil.fetchVariables(PdfConstants.MODEL); data.construct(); data.setModel(model); return data; } } 本篇文章只介绍同步打印,如果异步需要修改doExport方法。 编写导出的数据处理逻辑 @Ext(PdfPrintTask.class) public class PrintExportExt extends AbstractPdfExportFetchDataExtPointImpl implements PdfExportFetchDataExtPoint { // 这里使用扩展点表达式匹配需要打印的非存储模型,只有表达式为true才会走这段逻辑。 @Override @ExtPoint.Implement(expression = "context.model==\"" + ProductPricingClientTransient.MODEL_MODEL + "\"") public List<Object> fetchExportData(PdfPrintTask exportTask, PdfDefinitionContext context) { List<Object> result = new ArrayList<>(); List<Object> dataList = new ArrayList<>(); TransientPdfPrintTask transientPdfPrintTask = new TransientPdfPrintTask(); transientPdfPrintTask.set_d(exportTask.get_d()); dataList.add(transientPdfPrintTask.getBusinessData()); result.add(dataList); return result; } } 前端自定义打印按钮,将数据提交给业务数据字段,并使用同步导出打印。

    2025年10月13日
    40000
  • 如何实现业务表格跳转页面设计器设计器页面

    后端实现 代理继承界面设计器视图模型 @Model.model(MyView.MODEL_MODEL) @Model(displayName = "视图代理") @Model.Advanced(type = ModelTypeEnum.PROXY) public class MyView extends UiDesignerViewProxy { public static final String MODEL_MODEL = "hr.simple.MyView"; @Field.Integer @Field(displayName = "页面布局ID") private Long uiDesignerViewLayoutId; } 重写查询接口,返回页面布局ID,重写创建接口,实现创建页面逻辑。 package pro.shushi.pamirs.top.core.action; import org.apache.commons.collections4.CollectionUtils; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Component; import pro.shushi.pamirs.boot.base.constants.ViewConstants; import pro.shushi.pamirs.boot.base.enmu.ActionTargetEnum; import pro.shushi.pamirs.boot.base.ux.annotation.action.UxAction; import pro.shushi.pamirs.boot.base.ux.annotation.action.UxRoute; import pro.shushi.pamirs.boot.base.ux.annotation.button.UxRouteButton; import pro.shushi.pamirs.framework.connectors.data.sql.Pops; import pro.shushi.pamirs.framework.connectors.data.sql.query.LambdaQueryWrapper; import pro.shushi.pamirs.meta.annotation.Action; import pro.shushi.pamirs.meta.annotation.Function; import pro.shushi.pamirs.meta.annotation.Model; import pro.shushi.pamirs.meta.api.dto.condition.Pagination; import pro.shushi.pamirs.meta.api.dto.wrapper.IWrapper; import pro.shushi.pamirs.meta.api.session.PamirsSession; import pro.shushi.pamirs.meta.constant.FunctionConstants; import pro.shushi.pamirs.meta.enmu.*; import pro.shushi.pamirs.top.api.model.MyView; import pro.shushi.pamirs.ui.designer.api.designe.UiDesignerViewLayoutService; import pro.shushi.pamirs.ui.designer.model.UiDesignerViewLayout; import pro.shushi.pamirs.ui.designer.pmodel.UiDesignerViewLayoutProxy; import java.util.List; import java.util.Map; import java.util.stream.Collectors; /** * @author Yexiu at 20:39 on 2025/3/27 */ @Component @Model.model(MyView.MODEL_MODEL) public class MyViewAction { @Autowired private UiDesignerViewLayoutService uiDesignerViewLayoutService; @Action.Advanced(name = FunctionConstants.create, managed = true) @Action(displayName = "创建", summary = "添加", bindingType = ViewTypeEnum.FORM) @Function(name = FunctionConstants.create) @Function.fun(FunctionConstants.create) public MyView create(MyView data) { UiDesignerViewLayoutProxy uiDesignerViewLayoutProxy = new UiDesignerViewLayoutProxy(); uiDesignerViewLayoutProxy.setBizType(data.getBizType()); uiDesignerViewLayoutProxy.setDesignerActionBarType(data.getDesignerActionBarType()); uiDesignerViewLayoutProxy.setViewType(data.getType()); uiDesignerViewLayoutProxy.setModel(data.getModel()); uiDesignerViewLayoutProxy.setModule(PamirsSession.getServApp()); uiDesignerViewLayoutProxy.setViewTitle(data.getTitle()); uiDesignerViewLayoutProxy.setUsingDefaultView(data.getLoadLayout()); UiDesignerViewLayoutProxy saveUiDesigner = uiDesignerViewLayoutService.create(uiDesignerViewLayoutProxy); data.setDesignerViewId(saveUiDesigner.getId()); return data; } @Function.Advanced(type = FunctionTypeEnum.QUERY, displayName = "查询列表") @Function.fun(FunctionConstants.queryPage) @Function(openLevel = {FunctionOpenEnum.API, FunctionOpenEnum.LOCAL}) public Pagination<MyView> queryPage(Pagination<MyView> page, IWrapper<MyView> queryWrapper) { LambdaQueryWrapper<MyView> wrapper = Pops.<MyView>lambdaQuery().from(MyView.MODEL_MODEL) .eq(MyView::getSys, Boolean.FALSE) .eq(MyView::getSystemSource, SystemSourceEnum.UI); Pagination<MyView> myViewPagination = new MyView().queryPage(page, wrapper); List<MyView> content…

    2025年3月31日
    35300
  • 导入导出支持国际化语言分隔符

    需求 导出 Excel 时,所有整数、小数字段需要加千分位分隔符显示 例如:10000 导出成 10,000。 只影响“导出的显示效果”,不改变原始数据的语义。 实现思路 通过修改“ Excel 默认导出模版”的平台逻辑,将整型字段模版定义为文本类型,并自定义导出扩展,将所有整型字段的数据根据国际化配置进行分割。 代码示例 自定义导出扩展,分割整型字段 注意 所有已有的导出扩展必须修改继承类ExcelExportSameQueryPageTemplate<Object> –> GlobalExportExt<Object> 否则,已有的导出扩展生成的Excel将无法正常格式化整型字段。 package pro.shushi.pamirs.top.core.temp.exports; import org.apache.commons.collections4.CollectionUtils; import org.springframework.stereotype.Component; import pro.shushi.pamirs.file.api.context.ExcelDefinitionContext; import pro.shushi.pamirs.file.api.entity.EasyExcelBlockDefinition; import pro.shushi.pamirs.file.api.entity.EasyExcelCellDefinition; import pro.shushi.pamirs.file.api.entity.EasyExcelSheetDefinition; import pro.shushi.pamirs.file.api.extpoint.ExcelExportFetchDataExtPoint; import pro.shushi.pamirs.file.api.extpoint.impl.ExcelExportSameQueryPageTemplate; import pro.shushi.pamirs.file.api.model.ExcelExportTask; import pro.shushi.pamirs.meta.annotation.Ext; import pro.shushi.pamirs.meta.annotation.ExtPoint; import pro.shushi.pamirs.meta.api.dto.config.ModelFieldConfig; import pro.shushi.pamirs.meta.api.session.PamirsSession; import pro.shushi.pamirs.meta.enmu.TtypeEnum; import pro.shushi.pamirs.meta.util.FieldUtils; import pro.shushi.pamirs.resource.api.model.ResourceLang; import java.math.BigDecimal; import java.util.ArrayList; import java.util.List; import java.util.Map; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.ConcurrentMap; @Component @Ext(ExcelExportTask.class) public class GlobalExportExt<T> extends ExcelExportSameQueryPageTemplate<T> implements ExcelExportFetchDataExtPoint { @ExtPoint.Implement(priority = 1) @Override public List<Object> fetchExportData(ExcelExportTask exportTask, ExcelDefinitionContext context) { List<Object> results = super.fetchExportData(exportTask, context); if (CollectionUtils.isEmpty(results)) { return results; } return dataFormat(context, results); } public static List<Object> dataFormat(ExcelDefinitionContext context, List<Object> results) { ResourceLang resourceLang = new ResourceLang().setCode(PamirsSession.getLang()).queryOne(); if (resourceLang == null) { return results; } // 小数分隔符 String decimalPoint = resourceLang.getDecimalPoint(); // 整数分隔符 String thousandsSep = resourceLang.getThousandsSep(); // 数字分组规则(每组多少位,比如 "3") String groupingRule = resourceLang.getGroupingRule(); // 解析 groupSize,只做一次 int groupSize = 3; if (groupingRule != null && groupingRule.matches("\\d+")) { try { groupSize = Integer.parseInt(groupingRule); } catch (NumberFormatException ignore) { } } boolean needGroup = groupSize > 0 && thousandsSep != null && !thousandsSep.isEmpty(); //…

    2025年11月18日
    7900

Leave a Reply

登录后才能评论