{"componentChunkName":"component---src-templates-blog-post-js","path":"/blog/model-driven-form-pcf-javascript-client-scripting/","result":{"data":{"markdownRemark":{"frontmatter":{"title":"Model-driven apps: como estender o formulário com PCF e JavaScript","description":"Quando usar PCF, quando usar JavaScript no client API e quando ficar no no-code para estender formulários de model-driven apps sem comprometer performance e ALM.","date":"23 de agosto de 2026","thumbnail":null},"html":"<p>Quem opera model-driven apps em escala cedo ou tarde chega ao limite do que a configuração declarativa oferece. Business rules resolvem validações simples, colunas calculadas cobrem parte da lógica, mas há requisitos de interface — um mapa embutido, um seletor customizado, um cálculo em tempo real na tela — que exigem código no formulário. As duas ferramentas para isso são o <strong>PCF (PowerApps Component Framework)</strong> e o <strong>client scripting em JavaScript</strong> sobre o Client API. Elas não competem: resolvem problemas diferentes, e escolher errado gera dívida técnica cara.</p>\n<p><strong>O que cada abordagem realmente faz</strong></p>\n<p>O client scripting em JavaScript roda no contexto do formulário e reage a eventos: OnLoad, OnSave, OnChange de coluna, OnLookupTagClick. Você usa a <code>formContext</code> para ler e escrever atributos, mostrar/ocultar seções, disparar notificações e chamar a Web API. É a ferramenta certa para <em>comportamento</em> — orquestrar o formulário, validar antes de salvar, popular campos dependentes.</p>\n<p>O PCF é outra categoria: você substitui a renderização de um controle (uma coluna ou até um grid inteiro) por um componente próprio em TypeScript/React. É a ferramenta certa para <em>apresentação</em> — quando o controle nativo não existe ou não atende, e você precisa de um slider, um card visual, um input mascarado, um mapa. O PCF recebe o valor via <code>context.parameters</code> e devolve mudanças pelo <code>notifyOutputChanged</code>, mantendo o dado no Dataverse como fonte da verdade.</p>\n<p><strong>Quando NÃO escrever código</strong></p>\n<p>Antes de abrir o VS Code, confirme que o requisito não cabe em configuração:</p>\n<ul>\n<li>Validação condicional simples e mostrar/ocultar campos → <strong>business rules</strong> (funcionam também em canvas e são portáveis).</li>\n<li>Agregação de filhos, cálculo determinístico → <strong>rollup / formula columns</strong> em Power Fx.</li>\n<li>Formatação de coluna de escolha, rating, progress bar → muitos <strong>controles modernos nativos</strong> já existem sem PCF.</li>\n</ul>\n<p>Código só se justifica quando o no-code não alcança. Cada linha de JavaScript ou componente PCF é algo que alguém vai ter que manter, testar em cada release e revalidar quando a Microsoft mexer no client.</p>\n<p><strong>Boas práticas de client scripting que evitam dor</strong></p>\n<ol>\n<li><strong>Nunca use <code>Xrm.Page</code></strong> — está deprecado. Receba <code>executionContext</code> no handler e obtenha a <code>formContext</code> a partir dele.</li>\n<li><strong>Registre a função pela solução</strong>, associada a um web resource, não cole código inline. Isso é o que torna o script versionável e transportável entre ambientes.</li>\n<li><strong>OnSave assíncrono com cuidado</strong>: se precisar validar via Web API antes de salvar, use <code>PreventDefault</code> e ressalve após a resposta — bloquear o save de forma síncrona degrada a experiência.</li>\n<li><strong>Não chame Web API em loop</strong> dentro de OnChange; agrupe requisições e trate erro com feedback visível (<code>setFormNotification</code>).</li>\n</ol>\n<p><strong>PCF e o custo de ALM que ninguém conta</strong></p>\n<p>O PCF é poderoso, mas tem custo operacional real:</p>\n<ul>\n<li>Precisa de <strong>code components habilitados</strong> no ambiente (setting que nem sempre está ligado em produção).</li>\n<li>Componente PCF vive dentro de uma <strong>solução gerenciada</strong> — build com <code>pac pcf</code>, empacotamento e deploy pela pipeline, não upload manual.</li>\n<li>O <strong>bundle</strong> carregado no formulário afeta o tempo de load; um React pesado em cada abertura de registro multiplica a latência percebida.</li>\n<li>Componentes de terceiros baixados do PCF Gallery devem passar por revisão de segurança — eles rodam no contexto autenticado do usuário.</li>\n</ul>\n<p>Na prática: PCF para poucos controles de alto valor, bem versionados, e não como resposta padrão para toda customização de tela.</p>\n<p><strong>Roteiro de decisão rápido</strong></p>\n<ul>\n<li>Preciso mudar <em>comportamento</em> do formulário (validar, orquestrar, popular)? → <strong>JavaScript / Client API</strong>.</li>\n<li>Preciso mudar <em>como um dado é exibido ou editado</em> e o controle nativo não existe? → <strong>PCF</strong>.</li>\n<li>Dá pra resolver com business rule, rollup, formula column ou controle moderno nativo? → <strong>fique no no-code</strong>.</li>\n<li>É lógica de negócio que precisa rodar mesmo fora do formulário (via API, integração, importação)? → não é client-side: é <strong>plugin no Dataverse</strong>.</li>\n</ul>\n<p>Essa última linha é o erro mais comum que vemos: colocar regra crítica de negócio em JavaScript de formulário. Se o dado pode entrar por integração, importação ou outro app, o client script simplesmente não roda — a regra tem que estar no servidor.</p>\n<p>Extensão de model-driven apps é onde arquitetura e governança de ALM se encontram: escolher entre no-code, client script, PCF e plugin define o custo de manutenção dos próximos anos. Se sua equipe está avaliando até onde ir com código na Power Platform, a Dynamic Soluções ajuda a definir a arquitetura, estruturar o ALM em soluções gerenciadas e sustentar o ambiente com nossos planos de suporte.</p>\n<p>Anyone running model-driven apps at scale eventually hits the ceiling of what declarative configuration offers. Business rules handle simple validations, calculated columns cover part of the logic, but there are UI requirements — an embedded map, a custom picker, a real-time on-screen calculation — that require code on the form. The two tools for this are the <strong>PCF (PowerApps Component Framework)</strong> and <strong>client scripting in JavaScript</strong> over the Client API. They don't compete: they solve different problems, and picking the wrong one creates expensive technical debt.</p>\n<p><strong>What each approach actually does</strong></p>\n<p>JavaScript client scripting runs in the form context and reacts to events: OnLoad, OnSave, OnChange of a column, OnLookupTagClick. You use <code>formContext</code> to read and write attributes, show/hide sections, raise notifications and call the Web API. It's the right tool for <em>behavior</em> — orchestrating the form, validating before save, populating dependent fields.</p>\n<p>PCF is a different category: you replace the rendering of a control (a column or even an entire grid) with your own component in TypeScript/React. It's the right tool for <em>presentation</em> — when the native control doesn't exist or doesn't fit, and you need a slider, a visual card, a masked input, a map. PCF receives the value via <code>context.parameters</code> and pushes changes back through <code>notifyOutputChanged</code>, keeping the data in Dataverse as the source of truth.</p>\n<p><strong>When NOT to write code</strong></p>\n<p>Before opening VS Code, confirm the requirement doesn't fit in configuration:</p>\n<ul>\n<li>Simple conditional validation and show/hide fields → <strong>business rules</strong> (they also work in canvas and are portable).</li>\n<li>Child aggregation, deterministic calculation → <strong>rollup / formula columns</strong> in Power Fx.</li>\n<li>Choice column formatting, rating, progress bar → many <strong>modern native controls</strong> already exist without PCF.</li>\n</ul>\n<p>Code is only justified when no-code can't reach. Every line of JavaScript or PCF component is something someone will have to maintain, test on each release and revalidate whenever Microsoft changes the client.</p>\n<p><strong>Client scripting best practices that avoid pain</strong></p>\n<ol>\n<li><strong>Never use <code>Xrm.Page</code></strong> — it's deprecated. Receive <code>executionContext</code> in the handler and get <code>formContext</code> from it.</li>\n<li><strong>Register the function through the solution</strong>, tied to a web resource, don't paste inline code. That's what makes the script versionable and transportable across environments.</li>\n<li><strong>Async OnSave with care</strong>: if you need to validate via Web API before saving, use <code>PreventDefault</code> and re-save after the response — blocking the save synchronously degrades the experience.</li>\n<li><strong>Don't call the Web API in a loop</strong> inside OnChange; batch requests and handle errors with visible feedback (<code>setFormNotification</code>).</li>\n</ol>\n<p><strong>PCF and the ALM cost nobody counts</strong></p>\n<p>PCF is powerful, but it carries real operational cost:</p>\n<ul>\n<li>It needs <strong>code components enabled</strong> in the environment (a setting that isn't always turned on in production).</li>\n<li>A PCF component lives inside a <strong>managed solution</strong> — build with <code>pac pcf</code>, packaging and deploy through the pipeline, not manual upload.</li>\n<li>The <strong>bundle</strong> loaded on the form affects load time; a heavy React on every record open multiplies perceived latency.</li>\n<li>Third-party components pulled from the PCF Gallery must go through a security review — they run in the user's authenticated context.</li>\n</ul>\n<p>In practice: PCF for a few high-value, well-versioned controls, not as the default answer for every screen customization.</p>\n<p><strong>Quick decision guide</strong></p>\n<ul>\n<li>Do I need to change the form's <em>behavior</em> (validate, orchestrate, populate)? → <strong>JavaScript / Client API</strong>.</li>\n<li>Do I need to change <em>how a piece of data is displayed or edited</em> and the native control doesn't exist? → <strong>PCF</strong>.</li>\n<li>Can it be solved with a business rule, rollup, formula column or native modern control? → <strong>stay no-code</strong>.</li>\n<li>Is it business logic that must run even outside the form (via API, integration, import)? → it's not client-side: it's a <strong>Dataverse plugin</strong>.</li>\n</ul>\n<p>That last line is the most common mistake we see: putting critical business rules in form JavaScript. If data can come in via integration, import or another app, the client script simply doesn't run — the rule has to be on the server.</p>\n<p>Extending model-driven apps is where architecture and ALM governance meet: choosing between no-code, client script, PCF and plugin defines your maintenance cost for years to come. If your team is weighing how far to go with code on the Power Platform, Dynamic Soluções helps define the architecture, structure ALM in managed solutions and sustain the environment through our support plans.</p>"}},"pageContext":{"slug":"/blog/model-driven-form-pcf-javascript-client-scripting/","previousPost":null,"nextPost":{"frontmatter":{"title":"Power Pages: performance e SEO de portais externos na prática"},"fields":{"slug":"/blog/power-pages-performance-seo-portais-externos/"}}}},"staticQueryHashes":["2269431855"]}