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

주문 줄을 더하면 주문 번호 자동으로 채우기Fill the order ID automatically on new lines

상세 패널 안 그리드에 주문 번호(orderId) 없이 줄을 더해도 마스터 주문의 id가 자동으로 들어가요. keyFill 옵션 한 줄이면 돼요.Add a line without an order ID (orderId) to the grid inside a detail panel and the master order's id is filled in automatically. One keyFill option does it.

심화Advanced
직접 써 보기Live preview주문 줄을 더하면 주문 번호 자동으로 채우기Fill the order ID automatically on new lines

코드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="addLine">줄 더하기</button>
    <button type="button" id="showLines">줄 확인</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('addLine').addEventListener('click', () => actions.addLine(api));
document.getElementById('showLines').addEventListener('click', () => actions.showLines(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')}원`;
// 마스터 번호별로 패널 안 그리드를 모아 둬요. 버튼이 이 목록으로 줄을 더해요.
const inner = new Map();
let nextId = 100;
// 상세 패널 안에 진짜 그리드를 만들어요. attachGrid로 마스터에 이어 줘요.
const renderer = () => {
  let grid = null;
  let off;
  let id = 0;
  return {
    mount(element, { row, attachGrid }) {
      id = row.id;
      element.style.padding = '8px 16px';
      const host = document.createElement('div');
      host.style.height = '150px';
      element.replaceChildren(host);
      grid = MaxGrid.createGrid(host, {
        columns: [
          { id: 'orderId', title: '주문 번호', kind: 'number', width: 100 },
          { id: 'item', title: '상품', width: 140, editable: true },
          { 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} 주문 줄`,
      });
      inner.set(id, grid);
      off = attachGrid?.(grid);
    },
    update() { },
    destroy() {
      off?.();
      inner.delete(id);
      grid?.destroy();
      grid = null;
    },
  };
};
export const options = {
  columns: [
    { id: 'id', title: '주문 번호', kind: 'number', width: 100 },
    { id: 'customer', title: '고객', width: 130 },
    { id: 'status', title: '상태', width: 90 },
  ],
  rows,
  rowKey: 'id',
  // 안쪽 그리드에 새로 넣은 행의 orderId를 마스터의 id로 채워요.
  detail: { keyFill: { orderId: 'id' }, renderer, height: 230, expanded: [1] },
};
let logger = () => { };
export function setup(api, log) {
  logger = log;
  const off = api.on('detailChanged', ({ rowKey, expanded }) => {
    log({
      ko: `${rowKey}번 주문 상세를 ${expanded ? '열었어요' : '닫았어요'}`,
      en: `Order ${rowKey} details ${expanded ? 'opened' : 'closed'}`,
    });
  });
  return () => off();
}
export const actions = {
  addLine: (api) => {
    const row = api.getRows().find((r) => inner.has(r.id) && api.isDetailExpanded(r.id));
    const grid = row === undefined ? undefined : inner.get(row.id);
    if (row === undefined || grid === undefined) {
      logger({ ko: '먼저 주문 하나를 펼쳐 주세요', en: 'Open an order first' });
      return;
    }
    // orderId 없이 넣어요. 그리드가 마스터의 id로 채워 줘요.
    grid.addRows([{ id: nextId++, item: '새 상품', qty: 1, price: 1000 }]);
    logger({
      ko: `${row.id}번 주문에 orderId 없이 줄을 더했어요`,
      en: `Added a line to order ${row.id} without orderId`,
    });
  },
  showLines: (_api) => {
    for (const [id, grid] of inner) {
      for (const l of grid.getRows()) {
        logger(`orderId ${l.orderId} (${id}): ${l.item} x ${l.qty}, ${l.price}`);
      }
    }
  },
};

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="addLine">Add line</button>
    <button type="button" id="showLines">Show lines</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('addLine').addEventListener('click', () => actions.addLine(api));
document.getElementById('showLines').addEventListener('click', () => actions.showLines(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)}`;
// Keeps the grid of each panel by master id. The buttons use it to add lines.
const inner = new Map();
let nextId = 100;
// The panel holds a real grid. attachGrid connects it to the master.
const renderer = () => {
  let grid = null;
  let off;
  let id = 0;
  return {
    mount(element, { row, attachGrid }) {
      id = row.id;
      element.style.padding = '8px 16px';
      const host = document.createElement('div');
      host.style.height = '150px';
      element.replaceChildren(host);
      grid = MaxGrid.createGrid(host, {
        columns: [
          { id: 'orderId', title: 'Order ID', kind: 'number', width: 100 },
          { id: 'item', title: 'Item', width: 140, editable: true },
          { 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`,
      });
      inner.set(id, grid);
      off = attachGrid?.(grid);
    },
    update() { },
    destroy() {
      off?.();
      inner.delete(id);
      grid?.destroy();
      grid = null;
    },
  };
};
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',
  // A new row in the inner grid gets its orderId from the master id.
  detail: { keyFill: { orderId: 'id' }, renderer, height: 230, expanded: [1] },
};
let logger = () => { };
export function setup(api, log) {
  logger = log;
  const off = api.on('detailChanged', ({ rowKey, expanded }) => {
    log(`Order ${rowKey} details ${expanded ? 'opened' : 'closed'}`);
  });
  return () => off();
}
export const actions = {
  addLine: (api) => {
    const row = api.getRows().find((r) => inner.has(r.id) && api.isDetailExpanded(r.id));
    const grid = row === undefined ? undefined : inner.get(row.id);
    if (row === undefined || grid === undefined) {
      logger('Open an order first');
      return;
    }
    // Added without orderId. The grid fills it from the master id.
    grid.addRows([{ id: nextId++, item: 'New item', qty: 1, price: 1 }]);
    logger(`Added a line to order ${row.id} without orderId`);
  },
  showLines: (_api) => {
    for (const [id, grid] of inner) {
      for (const l of grid.getRows()) {
        logger(`orderId ${l.orderId} (${id}): ${l.item} x ${l.qty}, ${l.price}`);
      }
    }
  },
};