Custom Logic in CAP: Event Handlers, Hooks & Extensions

In SAP CAP, building applications is not only about modeling data with CDS but also about implementing custom logic to meet business requirements. Understanding CAP custom logic through event handlers, hooks, and extensions allows developers to create dynamic, maintainable, and scalable applications.

For structured hands-on learning, consider enrolling in a practical SAP course. Knowledge of SAP HANA enhances the performance of custom logic in production environments.

Understanding Event Handlers

Event handlers allow developers to intercept and process operations on entities or services. Events can be triggered for actions like CREATE, READ, UPDATE, DELETE (CRUD) or for custom actions and functions.

Example: Handling a CREATE event for Orders

this.on('CREATE', 'Orders', async (req) => {
  const { productID, quantity } = req.data;
  // Custom logic: validate stock before creation
  const product = await cds.run(SELECT.from('Products').where({ ID: productID }));
  if (product.stock < quantity) throw new Error('Insufficient stock');
});

This ensures that business rules are enforced before data is persisted.

Using Hooks

Hooks are functions triggered before or after standard operations, making it easy to implement reusable business logic. Common hooks include:

  • before CREATE/UPDATE/DELETE
  • after READ/UPDATE

Example: Updating inventory after an order is created

this.before('CREATE', 'Orders', async (req) => {
  await cds.run(UPDATE('Products')
    .set({ stock: { '-=': req.data.quantity } })
    .where({ ID: req.data.productID }));
});

Hooks make it easier to maintain centralized business rules rather than scattering logic across multiple places.

Leveraging Extensions

Extensions allow you to enhance existing services or entities without modifying the original definitions. This is particularly useful for multi-team projects or when extending SAP standard services.

Example: Extending a service to include a custom action

extend service CatalogService {
  action cancelOrder(orderID : UUID) returns Boolean;
}

Then implement the logic in your service handler:

this.on('cancelOrder', async (req) => {
  const { orderID } = req.data;
  await cds.run(UPDATE('Orders').set({ status: 'Cancelled' }).where({ ID: orderID }));
  return true;
});

Real-World Use Case

  1. Orders are created and validated with event handlers.
  2. Inventory is updated automatically using before hooks.
  3. New business actions like cancelOrder or shipOrder are added via service extensions.
  4. All custom logic remains modular, maintainable, and easily testable.

Best Practices

  • Keep event handlers focused and reusable
  • Use before/after hooks to centralize business rules
  • Apply extensions for service scalability without modifying base code
  • Document all custom logic to aid team collaboration
  • Combine with CDS annotations for validation and UI enhancements

Conclusion

Mastering CAP custom logic through event handlers, hooks, and extensions empowers developers to implement complex business rules while maintaining clean, scalable code. Combine this practical knowledge with an expert-led SAP course and deepen your backend understanding with SAP HANA to build production-ready CAP applications.

you may be interested in this blog here:-

Don’t Fear the Update: Navigating the Challenges of how to implement sap note

Five Top Technology Investment Drivers for 2024

How many dollars worth of RSU does Salesforce typically offer an MTS (experienced hire) on joining?

Integration cloud system to HANA Cloud Platform using Cloud Connector

₹25,000.00

SAP SD S4 HANA

SAP SD (Sales and Distribution) is a module in the SAP ERP (Enterprise Resource Planning) system that handles all aspects of sales and distribution processes. S4 HANA is the latest version of SAP’s ERP suite, built on the SAP HANA in-memory database platform. It provides real-time data processing capabilities, improved…
₹25,000.00

SAP HR HCM

SAP Human Capital Management (SAP HCM)  is an important module in SAP. It is also known as SAP Human Resource Management System (SAP HRMS) or SAP Human Resource (HR). SAP HR software allows you to automate record-keeping processes. It is an ideal framework for the HR department to take advantage…
₹25,000.00

Salesforce Administrator Training

I am text block. Click edit button to change this text. Lorem ipsum dolor sit amet, consectetur adipiscing elit. Ut elit tellus, luctus nec ullamcorper mattis, pulvinar dapibus leo.
₹25,000.00

Salesforce Developer Training

Salesforce Developer Training Overview Salesforce Developer training advances your skills and knowledge in building custom applications on the Salesforce platform using the programming capabilities of Apex code and the Visualforce UI framework. It covers all the fundamentals of application development through real-time projects and utilizes cases to help you clear…
₹25,000.00

SAP EWM

SAP EWM stands for Extended Warehouse Management. It is a best-of-breed WMS Warehouse Management System product offered by SAP. It was first released in 2007 as a part of SAP SCM meaning Supply Chain Management suite, but in subsequent releases, it was offered as a stand-alone product. The latest version…
₹25,000.00

Oracle PL-SQL Training Program

Oracle PL-SQL is actually the number one database. The demand in market is growing equally with the value of the database. It has become necessary for the Oracle PL-SQL certification to get the right job. eLearning Solutions is one of the renowned institutes for Oracle PL-SQL in Pune. We believe…
₹25,000.00

Pega Training Courses in Pune- Get Certified Now

Course details for Pega Training in Pune Elearning solution is the best PEGA training institute in Pune. PEGA is one of the Business Process Management tool (BPM), its development is based on Java and OOP concepts. The PAGA technology is mainly used to improve business purposes and cost reduction. PEGA…
₹27,000.00

SAP PP (Production Planning) Training Institute

SAP PP Training Institute in Pune SAP PP training (Production Planning) is one of the largest functional modules in SAP. This module mainly deals with the production process like capacity planning, Master production scheduling, Material requirement planning shop floor, etc. The PP module of SAP takes care of the Master…
X
WhatsApp WhatsApp us
Call Now Button