본문으로 건너뛰기Skip to content
예제 첫화면Examples home

주문마다 나눠 저장하고 실패한 주문만 남기기Save each order separately and keep only failures

saveDetails()가 주문마다 저장 함수를 불러요. 성공한 주문은 변경 표시가 지워지고, 실패한 주문은 표시가 남아 다시 저장할 수 있어요. 3번 주문은 일부러 실패해요.saveDetails() calls the save function once per order. Saved orders lose their change marks; failed orders keep them so you can retry. Order 3 fails on purpose.

심화Advanced
직접 써 보기Live preview주문마다 나눠 저장하고 실패한 주문만 남기기Save each order separately and keep only failures

코드Code

탭을 골라 코드를 복사하세요. 위 화면은 이 코드를 그대로 실행한 결과예요.Pick a tab and copy the code. The preview above runs exactly this code.

이 화면은 새 모양 옵션을 켠 모양이에요: density: 'spacious', iconStyle: 'soft', motion: true (코드에 없으면 기본 모양으로 보여요)This preview has the new-look options on: density: 'spacious', iconStyle: 'soft', motion: true (without them in your code you get the default look)

빌드 도구(Vite 등)를 쓰는 프로젝트용 모듈 파일이에요. 설치 없이 바로 돌려 보려면 HTML 탭이나 직접 해보기를 쓰세요.

버튼을 누르면 이 예제의 코드가 StackBlitz나 CodeSandbox로 전송돼요. 누르기 전에는 아무것도 보내지 않아요.

index.html
<div id="app">
  <div class="toolbar">
    <button type="button" id="saveAll">모두 저장</button>
    <button type="button" id="saveFirst">1번만 저장</button>
  </div>
  <div id="grid" style="height: 480px"></div>
</div>
<script type="module" src="./main.js"></script>
main.js
import { createGrid } from 'maxgrid';
import { actions, options, setup } from './example';
const api = createGrid(document.getElementById('grid'), options);
setup(api, console.log);
document.getElementById('saveAll').addEventListener('click', () => actions.saveAll(api));
document.getElementById('saveFirst').addEventListener('click', () => actions.saveFirst(api));
example.js
const rows = [
  { id: 1, customer: '김하늘', status: '준비' },
  { id: 2, customer: '이도윤', status: '배송' },
  { id: 3, customer: '박서연', status: '완료' },
  { id: 4, customer: '최지우', status: '준비' },
];
const lines = [
  { id: 11, orderId: 1, item: '볼펜', qty: 1, price: 4000 },
  { id: 12, orderId: 1, item: '노트', qty: 2, price: 6000 },
  { id: 13, orderId: 1, item: '스테이플러', qty: 3, price: 9000 },
  { id: 21, orderId: 2, item: '파일철', qty: 2, price: 3000 },
  { id: 22, orderId: 2, item: '포스트잇', qty: 3, price: 2000 },
  { id: 31, orderId: 3, item: '마커', qty: 1, price: 5000 },
  { id: 32, orderId: 3, item: '테이프', qty: 2, price: 3000 },
  { id: 33, orderId: 3, item: '가위', qty: 3, price: 7000 },
  { id: 41, orderId: 4, item: '클립', qty: 2, price: 1000 },
  { id: 42, orderId: 4, item: '형광펜', qty: 3, price: 2000 },
];
const won = (v) => `${Number(v).toLocaleString('ko-KR')}원`;
// 상세 패널 안에 진짜 그리드를 만들어요. attachGrid로 마스터에 이어 줘요.
const renderer = () => {
  let grid = null;
  let off;
  return {
    mount(element, { row, attachGrid }) {
      element.style.padding = '8px 16px';
      const host = document.createElement('div');
      host.style.height = '130px';
      element.replaceChildren(host);
      grid = MaxGrid.createGrid(host, {
        columns: [
          { id: 'item', title: '상품', width: 140 },
          { id: 'qty', title: '수량', kind: 'number', width: 80, editable: true },
          {
            id: 'price',
            title: '단가',
            kind: 'number',
            width: 110,
            editable: true,
            formatValue: won,
          },
        ],
        rows: lines.filter((l) => l.orderId === row.id),
        rowKey: 'id',
        saveMode: 'batch',
        ariaLabel: `${row.customer} 주문 줄`,
      });
      off = attachGrid?.(grid);
    },
    update() { },
    destroy() {
      off?.();
      grid?.destroy();
      grid = null;
    },
  };
};
// 서버 대신 300ms 기다리는 저장 함수예요. 3번 주문은 일부러 실패해요.
const save = ({ rowKey }) => new Promise((resolve, reject) => {
  setTimeout(() => {
    if (rowKey === 3)
      reject(new Error('server error'));
    else
      resolve();
  }, 300);
});
export const options = {
  columns: [
    { id: 'id', title: '주문 번호', kind: 'number', width: 100 },
    { id: 'customer', title: '고객', width: 130 },
    { id: 'status', title: '상태', width: 90 },
  ],
  rows,
  rowKey: 'id',
  detail: { splitSave: { save }, renderer, height: 190, expanded: [1, 3] },
};
let logger = () => { };
export function setup(api, log) {
  logger = log;
  const offs = [
    api.on('detailSaved', ({ rowKey, added, updated, removed }) => {
      log({
        ko: `${rowKey}번 주문 저장 완료 (추가 ${added}, 수정 ${updated}, 삭제 ${removed})`,
        en: `Order ${rowKey} saved (added ${added}, updated ${updated}, removed ${removed})`,
      });
    }),
    api.on('detailSaveFailed', ({ rowKey, error }) => {
      const reason = error instanceof Error ? error.message : String(error);
      log({
        ko: `${rowKey}번 주문 저장 실패: ${reason}. 변경 표시는 그대로 남아요`,
        en: `Order ${rowKey} save failed: ${reason}. Its marks stay`,
      });
    }),
  ];
  return () => offs.forEach((off) => off());
}
export const actions = {
  saveAll: async (api) => {
    const { saved, failed } = await api.saveDetails();
    logger({
      ko: `저장한 주문: [${saved.join(', ')}], 실패한 주문: [${failed.join(', ')}]`,
      en: `Saved orders: [${saved.join(', ')}], failed orders: [${failed.join(', ')}]`,
    });
  },
  saveFirst: async (api) => {
    const { saved, failed } = await api.saveDetails(1);
    logger({
      ko: `1번 주문만 저장했어요. 저장 [${saved.join(', ')}], 실패 [${failed.join(', ')}]`,
      en: `Saved order 1 only. Saved [${saved.join(', ')}], failed [${failed.join(', ')}]`,
    });
  },
};

Module files for a project with a bundler such as Vite. To run it with no setup, use the HTML tab or Try it.

When you click, the example code is sent to StackBlitz or CodeSandbox. Nothing is sent before you click.

index.html
<div id="app">
  <div class="toolbar">
    <button type="button" id="saveAll">Save all</button>
    <button type="button" id="saveFirst">Save order 1</button>
  </div>
  <div id="grid" style="height: 480px"></div>
</div>
<script type="module" src="./main.js"></script>
main.js
import { createGrid } from 'maxgrid';
import { actions, options, setup } from './example';
const api = createGrid(document.getElementById('grid'), options);
setup(api, console.log);
document.getElementById('saveAll').addEventListener('click', () => actions.saveAll(api));
document.getElementById('saveFirst').addEventListener('click', () => actions.saveFirst(api));
example.js
const rows = [
  { id: 1, customer: 'Liam Carter', status: 'Pending' },
  { id: 2, customer: 'Emma Stone', status: 'Shipping' },
  { id: 3, customer: 'Noah Reed', status: 'Done' },
  { id: 4, customer: 'Olivia Hayes', status: 'Pending' },
];
const lines = [
  { id: 11, orderId: 1, item: 'Pen', qty: 1, price: 4 },
  { id: 12, orderId: 1, item: 'Notebook', qty: 2, price: 6 },
  { id: 13, orderId: 1, item: 'Stapler', qty: 3, price: 9 },
  { id: 21, orderId: 2, item: 'Binder', qty: 2, price: 3 },
  { id: 22, orderId: 2, item: 'Sticky notes', qty: 3, price: 2 },
  { id: 31, orderId: 3, item: 'Marker', qty: 1, price: 5 },
  { id: 32, orderId: 3, item: 'Tape', qty: 2, price: 3 },
  { id: 33, orderId: 3, item: 'Scissors', qty: 3, price: 7 },
  { id: 41, orderId: 4, item: 'Clips', qty: 2, price: 1 },
  { id: 42, orderId: 4, item: 'Highlighter', qty: 3, price: 2 },
];
const dollars = (v) => `$${Number(v)}`;
// The panel holds a real grid. attachGrid connects it to the master.
const renderer = () => {
  let grid = null;
  let off;
  return {
    mount(element, { row, attachGrid }) {
      element.style.padding = '8px 16px';
      const host = document.createElement('div');
      host.style.height = '130px';
      element.replaceChildren(host);
      grid = MaxGrid.createGrid(host, {
        columns: [
          { id: 'item', title: 'Item', width: 140 },
          { id: 'qty', title: 'Qty', kind: 'number', width: 80, editable: true },
          {
            id: 'price',
            title: 'Unit price',
            kind: 'number',
            width: 110,
            editable: true,
            formatValue: dollars,
          },
        ],
        rows: lines.filter((l) => l.orderId === row.id),
        rowKey: 'id',
        saveMode: 'batch',
        ariaLabel: `${row.customer} order lines`,
      });
      off = attachGrid?.(grid);
    },
    update() { },
    destroy() {
      off?.();
      grid?.destroy();
      grid = null;
    },
  };
};
// A save function that waits 300 ms instead of calling a server. Order 3 fails on purpose.
const save = ({ rowKey }) => new Promise((resolve, reject) => {
  setTimeout(() => {
    if (rowKey === 3)
      reject(new Error('server error'));
    else
      resolve();
  }, 300);
});
export const options = {
  columns: [
    { id: 'id', title: 'Order ID', kind: 'number', width: 100 },
    { id: 'customer', title: 'Customer', width: 130 },
    { id: 'status', title: 'Status', width: 90 },
  ],
  rows,
  rowKey: 'id',
  detail: { splitSave: { save }, renderer, height: 190, expanded: [1, 3] },
};
let logger = () => { };
export function setup(api, log) {
  logger = log;
  const offs = [
    api.on('detailSaved', ({ rowKey, added, updated, removed }) => {
      log(`Order ${rowKey} saved (added ${added}, updated ${updated}, removed ${removed})`);
    }),
    api.on('detailSaveFailed', ({ rowKey, error }) => {
      const reason = error instanceof Error ? error.message : String(error);
      log(`Order ${rowKey} save failed: ${reason}. Its marks stay`);
    }),
  ];
  return () => offs.forEach((off) => off());
}
export const actions = {
  saveAll: async (api) => {
    const { saved, failed } = await api.saveDetails();
    logger(`Saved orders: [${saved.join(', ')}], failed orders: [${failed.join(', ')}]`);
  },
  saveFirst: async (api) => {
    const { saved, failed } = await api.saveDetails(1);
    logger(`Saved order 1 only. Saved [${saved.join(', ')}], failed [${failed.join(', ')}]`);
  },
};