728x90
이번 글에서는 편집용 폼의 Select Category에 설정된 값을 디폴트로 표시하여, 값을 편집하지 않아도 일일이 수정할 필요가 없도록 하는 방법을 알아보겠습니다.
1. 선택 옵션 동적으로 설정하기
Express를 사용하지 않는 경우, 일반적으로 <option> 태그에 불리언 속성인 selected를 추가하여 디폴트 값을 설정합니다. 이를 통해 옵션이 제공되면 해당 옵션을 선택하게 됩니다.
<!-- Edit.ejs -->
<select id="category" name="category" required>
<option value="fruit" <%=product.category === 'fruit' ? 'selected': ''%>>fruit</option>
<option value="vegetable" <%=product.category === 'vegetable' ? 'selected': ''%>>vegetable</option>
<option value="dairy" <%=product.category === 'dairy' ? 'selected': ''%>>dairy</option>
</select>
<!-- new.ejs -->
<select id="category" name="category" required>
<% for (let category of categories) { %>
<option value="<%=category%>"><%=category%></option>
<% } %>
</select>
위 코드에서는 카테고리 값이 product.category와 같으면 selected 속성을 추가하여 해당 옵션을 선택하도록 동적으로 설정합니다.
2. 카테고리 목록 동적 생성
index.js 파일에서 카테고리 목록을 동적으로 생성하는 루프를 사용하여 옵션을 생성합니다.
// index.js
const categories = ['fruit', 'vegetable','dairy'];
// 다른 코드 생략
app.get('/products/new', (req, res) => {
res.render('products/new', { categories })
});
app.get('/products/:id/edit', async (req, res) => {
try {
const { id } = req.params;
const { product } = await Product.findById(id);
res.render('edit', { product, categories });
} catch (error) {
console.error(error);
res.status(500).send('Internal Server Error');
}
});
제품 추가해보기
// index.js
const categories = ['fruit', 'vegetable','dairy', 'fugi','mushroom'];
이제 동적으로 selected 속성을 사용하기위해 아래와 같이 수정해줍시다.
// edit.ejs
<select name="category" id="category">
<% for (let category of categories) { %>
<option value="<%= category %>" <%= product.category === category ? 'selected' : '' %>><%= category %></option>
<% } %>
</select>
//index.js
app.get('/products/:id/edit', async (req, res) => {
const { id } = req.params;
const product = await Product.findById(id);
res.render('products/edit', { product , categories}) //categories 추가
})
만약 새로운 카테고리를 추가한다면 다 적용되는지도 확인해봅시다.
// index.js
const categories = ['fruit', 'vegetable','dairy', 'baked goods'];
새로고침 후 Edit & New 확인
마지막으로 새로 제품을 추가하는 링크를 만들고 마무리 하겠습니다.
// index.ejs
<ul>
// 생략
</ul>
<a href="/products/new">New Product</a>
이제 새로운 상품을 생성하거나 상품을 편집할 때, 카테고리 목록이 동적으로 생성되어 옵션으로 제공됩니다.
이렇게 함으로써, 편집용 폼의 카테고리를 선택하거나 수정할 때 일일이 코드를 수정하지 않고도 효율적으로 작업할 수 있게 되었습니다.
다음 글에서는 더 나은 편집용 폼을 위한 내용과 삭제 기능에 대해 배워보겠습니다. 기대해 주세요!
728x90
'백엔드(Backend) > 데이터베이스' 카테고리의 다른 글
[MongoDB] 카테고리별로 필터링하기 (0) | 2023.12.18 |
---|---|
[MongoDB] 프로덕트 삭제하기 (0) | 2023.12.16 |
[MongoDB] 프로덕트 업데이트하기 (0) | 2023.12.14 |
[MongoDB] 프로덕트 만들기: 새로운 상품 추가하기 (0) | 2023.12.13 |
[MongoDB] Express와 Mongoose로 상품 상세 정보 라우트 만들기 (0) | 2023.12.12 |