Consider a default Frappe docType. The layout on screen of the data is not changeable. I would like to add an extra layer, so I can drag and drop the layout of a docType.
Assistant
Other models, same or similar prompt
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.
To customize the layout of a Frappe DocType, you can create a Web Form or a custom JavaScript file that overrides the default layout. While this won't provide a true drag-and-drop interface, it will allow you to change the layout to suit your needs. Here's a general outline of how you can proceed:
Option 1: Create a Web Form
Log in to your Frappe/ERPNext instance.
Go to "Web Form" List (search for it in the search bar).
Click "New" to create a new Web Form.
Select the DocType you want to customize from the "Document Type" dropdown.
Customize the layout by adding/removing/reordering fields using the "Add Row" and drag-and-drop features.
Save and publish the Web Form.
Now, you can use this Web Form as the primary interface for interacting with the DocType. The layout changes made in the Web Form will only apply to this specific form, not the default DocType layout.
Option 2: Custom JavaScript
Log in to your Frappe/ERPNext instance.
Go to "Customize Form" (search for it in the search bar).
Select the DocType you want to customize from the "Select DocType" dropdown.
In the "Customize Form" window, scroll down to the "Client Script" section.
Write custom JavaScript to manipulate the form layout based on your requirements. For example:
js
frappe.ui.form.on('Your DocType', {
refresh(frm) {
// Your custom code to manipulate form layout
// Example: Move the "field1" after "field2"
frm.move_field('field1', 'field2');
}
});
Save your changes.
Keep in mind that this approach requires some JavaScript knowledge and may be less user-friendly than the Web Form option. However, it provides more control over the layout and behavior of the form.
Please note that neither of these options provides a true drag-and-drop interface for end-users, but they do allow you to customize the layout of your DocType to suit your needs.
User
Is there an approach where placeholder objects are used, to achieve true drag and drop functionality and user friendliness?
Assistant
To achieve true drag-and-drop functionality with a user-friendly interface, you can create a custom app that uses placeholder objects and a front-end JavaScript library like jQuery UI or GridStack to create a layout builder for your Frappe DocType. Here's an outline of the steps you can follow:
Create a new custom Frappe app:
javascript
$ bench new-app custom_layout_builder
Follow the prompts to set up your app.
2. Install the app in your Frappe/ERPNext instance:
Inside your custom app, create a new DocType to store the custom layouts. Add fields like doctype, name, and a JSON field to store the layout information.
Add the necessary front-end libraries (e.g., jQuery UI or GridStack) to your app's public folder.
Create a new Page or Web Template in your custom app for the layout builder. In this page, use the front-end library to enable drag-and-drop functionality for the fields of the selected DocType. You can use placeholder objects to represent the fields.
For each field, create a draggable object containing the field label and a unique identifier (e.g., field name). Place these objects in a grid or container, and enable the drag-and-drop functionality using the chosen library.
6. When a user finishes customizing the layout, save the positions and arrangement of the fields in JSON format, and store it in the custom layout DocType created in step 3.
7. Override the default rendering of the target DocType by using a custom script or modifying its controller. Load the custom layout JSON from the custom layout DocType, and apply the saved layout information while rendering the form. This can be done by manipulating the DOM structure or programmatically changing the field positions based on the saved layout.
8. Finally, make sure that your custom app is included in your site's build by adding it to the apps.txt file in the sites directory.
While this approach requires more development work, it will provide a user-friendly drag-and-drop interface for customizing DocType layouts in your Frappe/ERPNext instance. Users can use this interface to modify the layout without needing to write any code.
User
Please give a list of tests that should be written in order to ensure proper functioning.
Assistant
To ensure the proper functioning of the custom drag-and-drop layout builder, you should write tests covering various aspects of the application. Here's a list of tests that you should consider writing:
Custom Layout DocType:
Test the creation and retrieval of custom layout records.
Test the validation of JSON layout data.
Layout Builder Page/Web Template:
Test loading the layout builder page with the correct front-end libraries (e.g., jQuery UI or GridStack).
Test rendering the fields of the selected DocType as draggable placeholder objects.
Test the drag-and-drop functionality, ensuring that fields can be moved and rearranged within the container.
Test the saving of the custom layout, ensuring that the arrangement of fields is correctly saved in JSON format.
Custom Layout Application:
Test loading the custom layout JSON for a specific DocType when rendering the form.
Test applying the custom layout to the form, ensuring that the fields are displayed in the correct positions.
Test handling cases where the custom layout JSON is invalid or missing.
Permissions and Access Control:
Test that only users with appropriate permissions can access the layout builder and customize layouts.
Test that only users with appropriate permissions can view or modify the custom layout records in the Custom Layout DocType.
Cross-Browser Compatibility:
Test the functionality of the layout builder in various browsers (e.g., Chrome, Firefox, Safari, Edge) to ensure compatibility.
Responsiveness:
Test the responsiveness of the layout builder interface on different screen sizes and devices.
Performance:
Test the performance of the layout builder, ensuring that it works smoothly even with a large number of fields.
Test the impact of applying custom layouts on the loading time and performance of the DocType forms.
When writing these tests, use Frappe's testing framework to create test cases for the back-end (Python) and front-end (JavaScript) components. This will help you catch issues early on in the development process and ensure the stability of your custom drag-and-drop layout builder.
User
Please provide the most important code snippets to create this application, first list them in a numbered list, and then provide the code for number 1-4.
Assistant
Here's a numbered list of the most important code snippets for creating the custom drag-and-drop layout builder application:
Create a new Custom Layout DocType with fields for storing the layout information.
Add necessary front-end libraries to your app's public folder.
Create a new Page or Web Template for the layout builder with draggable objects for each field.
Save the custom layout as JSON data in the Custom Layout DocType.
Override the default rendering of the target DocType and apply the custom layout.
Now, let's provide the code snippets for numbers 1-4:
Create a new Custom Layout DocType:
In your custom app, create a new DocType called Custom Layout. Add the following fields:
doctype: Link field to store the target DocType name.
layout_name: Data field to store the name of the layout.
layout_data: JSON field to store the layout information.
Add necessary front-end libraries to your app's public folder:
For this example, we'll use GridStack. Download the necessary files from https://github.com/gridstack/gridstack.js and place them in your custom app's public folder.
Create a new Page or Web Template for the layout builder with draggable objects for each field:
In your custom app, create a new page called layout_builder.html. In this file, include the GridStack library, create a container for the fields, and initialize the GridStack library:
html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Layout Builder</title>
<link rel="stylesheet" href="/assets/css/gridstack.min.css" />
</head>
<body>
<div class="grid-stack"></div>
<script src="/assets/js/gridstack-h5.min.js"></script>
<script>
document.addEventListener("DOMContentLoaded", function() {
const grid = GridStack.init();
// Add draggable field placeholders to the grid.
// Load the fields from the selected DocType.
// ...
});
</script>
</body>
</html>
User
Please give the snipper for number 5
Assistant
Override the default rendering of the target DocType and apply the custom layout:
Create a custom script file for your target DocType (e.g., sales_order_custom.js) in your custom app's public/js folder. In this file, override the refresh event, load the custom layout JSON data, and apply it to the form using JavaScript.
javascript
frappe.ui.form.on('Sales Order', {
refresh: function(frm) {
// Load the custom layout data from the Custom Layout DocType
frappe.call({
method: 'frappe.client.get_list',
args: {
doctype: 'Custom Layout',
fields: ['layout_data'],
filters: {
'doctype': frm.doctype,
'layout_name': 'Custom Layout 1' // Replace with the desired layout name
},
},
callback: function(response) {
if (response && response.message && response.message.length > 0) {
// Parse the layout JSON data and apply it to the form
const layoutData = JSON.parse(response.message[0].layout_data);
applyCustomLayout(frm, layoutData);
}
}
});
}
});
function applyCustomLayout(frm, layoutData) {
// Iterate through the layout data and update the field positions
layoutData.forEach(function(item) {
const fieldName = item.id; // Assuming the field name is stored in the 'id' attribute
const field = frm.fields_dict[fieldName];
if (field) {
// Update the field position in the form layout
field.wrapper.classList.add('grid-stack-item');
field.wrapper.setAttribute('data-gs-x', item.x);
field.wrapper.setAttribute('data-gs-y', item.y);
field.wrapper.setAttribute('data-gs-width', item.width);
field.wrapper.setAttribute('data-gs-height', item.height);
// Optionally, you can set the field's visibility based on the layout data
if (item.hidden) {
field.wrapper.style.display = 'none';
} else {
field.wrapper.style.display = 'block';
}
}
});
// Initialize the GridStack library for the form layout (read-only mode)
const grid = GridStack.init({
staticGrid: true,
alwaysShowResizeHandle: false,
acceptWidgets: false
}, frm.layout.wrapper);
}
User
Please provide the necessary code samples for tests for number 1 in the list.
Assistant
Here's a code snippet for a test case for the Custom Layout DocType (number 1 in the list). This test will create, retrieve, and validate the custom layout records. Create a new file called test_custom_layout.py in your custom app's tests folder and add the following code:
This test case creates a new Custom Layout record with sample layout data, saves it, and then retrieves the saved record to validate the data. The setUp method initializes some test data, including a random layout name and sample layout data. The test_create_and_retrieve_custom_layout method performs the actual testing.
To run the test, execute the following command in your Frappe/ERPNext instance:
Replace your-site-name with the name of your site, and make sure to use the correct app name if you named your custom app differently.
User
Please provide the necessary code samples for tests for number 2 in the list.
Assistant
To test the front-end libraries (number 2 in the list), you'll need to create JavaScript tests using a testing library, such as Jest or Mocha. In this example, we'll use Jest. First, set up Jest in your custom app:
Create a .babelrc file in your custom app's root folder with the following content:
json
{
"presets": ["@babel/preset-env"]
}
Update the scripts section in your package.json file to include a script for running Jest:
json
"scripts": {
"test": "jest"
}
Now, let's create a test for checking if the GridStack library is properly loaded and initialized. Create a new file called gridstack.test.js in your custom app's tests folder:
javascript
// custom_layout_builder/tests/gridstack.test.js
import { GridStack } from 'gridstack';
import 'gridstack/dist/h5/gridstack-dd-native';
describe('GridStack Library', () => {
let container;
beforeEach(() => {
// Create a container for the GridStack grid
container = document.createElement('div');
container.classList.add('grid-stack');
document.body.appendChild(container);
});
afterEach(() => {
// Clean up the container after each test
container.remove();
});
test('GridStack should be properly loaded', () => {
expect(GridStack).toBeDefined();
});
test('GridStack should initialize without errors', () => {
const grid = GridStack.init({ staticGrid: true }, container);
expect(grid).toBeInstanceOf(GridStack);
});
});
This test suite checks if the GridStack library is properly loaded and if it can be initialized without errors using a sample container. The beforeEach and afterEach methods are used to set up and clean up the container for each test.
To run the tests, execute the following command in your custom app's root folder:
bash
$ npm test
Make sure to import the necessary GridStack files in your custom app's public folder and update the import statements in the test file accordingly.
User
Please provide the necessary code samples for tests for number 3 in the list.
Assistant
To test the layout builder page and draggable objects for each field (number 3 in the list), you can use a testing library like Jest along with a DOM manipulation library like jsdom. We'll continue with the Jest setup from the previous answer.
First, install the required dependencies:
bash
$ npm install --save-dev jsdom
Next, create a helper function to load the layout builder page in a simulated browser environment using jsdom. Create a file called load_layout_builder.js in your custom app's tests folder:
javascript
// custom_layout_builder/tests/load_layout_builder.js
const { JSDOM } = require('jsdom');
const fs = require('fs');
const path = require('path');
async function loadLayoutBuilder() {
// Load the layout builder HTML file
const layoutBuilderPath = path.join(__dirname, '..', 'public', 'layout_builder.html');
const layoutBuilderHtml = fs.readFileSync(layoutBuilderPath, 'utf-8');
// Initialize a new JSDOM instance with the layout builder HTML
const dom = new JSDOM(layoutBuilderHtml, {
runScripts: 'dangerously',
resources: 'usable',
url: 'http://localhost/'
});
// Wait for the document to be fully loaded
await new Promise((resolve) => {
dom.window.document.addEventListener('DOMContentLoaded', resolve);
});
return dom;
}
module.exports = loadLayoutBuilder;
Now, create a test file called layout_builder.test.js in your custom app's tests folder:
javascript
User
Please provide the necessary code samples for tests for number 4 in the list.
Assistant
To test saving the custom layout as JSON data in the Custom Layout DocType (number 4 in the list), you can use Jest along with the frappejs library to simulate the Frappe environment. First, install the required dependencies:
Next, create a helper function to set up a simulated Frappe environment using frappejs. Create a file called setup_frappe_environment.js in your custom app's tests folder:
javascript
// custom_layout_builder/tests/setup_frappe_environment.js
const frappe = require('frappejs');
const SQLite = require('sqlite3').verbose();
async function setupFrappeEnvironment() {
if (!frappe.db) {
// Initialize the database
const db = new SQLite.Database(':memory:');
await frappe.init(db);
// Load the Custom Layout DocType
const CustomLayout = require('../models/custom_layout');
frappe.registerModel(CustomLayout);
// Initialize the Frappe client
const FrappeClient = require('frappejs-client').Client;
frappe.fetch = new FrappeClient({ server: 'http://localhost:8000' }).fetch.bind(frappe);
}
}
module.exports = setupFrappeEnvironment;
Update the path to the Custom Layout DocType model based on your custom app's folder structure.
Now, create a test file called save_layout.test.js in your custom app's tests folder:
javascript
User
Please provide the necessary code samples for tests for number 5 in the list.
Assistant
To test the front-end code for applying the custom layout to a DocType form (number 5 in the list), you can use Jest along with jsdom to simulate a browser environment. Continue with the Jest setup from the previous answers.
First, create a helper function to simulate the Frappe environment and load a DocType form. Create a file called load_doctype_form.js in your custom app's tests folder:
This test suite loads a simulated DocType form with a custom layout using the helper function, and checks if the form is rendered with the custom layout, including the position and size of each field.
To run the tests, execute the following command in your custom app's root folder:
bash
$ npm test
Make sure to update the import statements and file paths in the helper function and test file to match your custom app's folder structure, and adjust the code in your custom layout form rendering library (e.g., custom_layout_form.js) to work with the simulated browser environment in jsdom.
Replace the ... with the code to load the fields from the selected DocType, create draggable objects for each field, and add them to the grid.
Save the custom layout as JSON data in the Custom Layout DocType:
When the user finishes customizing the layout, serialize the GridStack layout as JSON data and save it in the Custom Layout DocType. You can use Frappe's API to create or update a Custom Layout document with the layout data.
Replace grid.save() with the appropriate GridStack method to serialize the layout data.
This code snippet loads the custom layout JSON data for the specified DocType and layout name, and applies the layout to the form by updating the field positions using GridStack. The GridStack library is initialized in read-only mode, so users won't be able to modify the layout directly on the form. Instead, they should use the layout builder created in the previous steps to customize the layout.
Make sure to include the necessary GridStack CSS and JS files in your custom app's public folder, as well as reference them in your custom script file, if necessary.
// custom_layout_builder/tests/layout_builder.test.js
const loadLayoutBuilder = require('./load_layout_builder');
describe('Layout Builder Page', () => {
let dom, window, document;
beforeEach(async () => {
dom = await loadLayoutBuilder();
window = dom.window;
document = window.document;
});
test('GridStack should be initialized on the layout builder page', () => {
const grid = window.GridStack.getGrids()[0];
expect(grid).toBeDefined();
});
test('Draggable field placeholders should be added to the grid', () => {
const gridItems = document.querySelectorAll('.grid-stack-item');
expect(gridItems.length).toBeGreaterThan(0);
});
// Add more tests to check the drag-and-drop functionality, layout saving, etc.
});
This test suite loads the layout builder page using the helper function, and checks if GridStack is initialized and if draggable field placeholders are added to the grid. You can add more tests to check the drag-and-drop functionality, layout saving, and other aspects of the layout builder.
To run the tests, execute the following command in your custom app's root folder:
bash
$ npm test
Make sure to update the file paths in the load_layout_builder.js helper function to match your custom app's folder structure, and adjust the code in your layout builder page (e.g., layout_builder.html) to work with the simulated browser environment in jsdom.
This test suite sets up a simulated Frappe environment, saves a custom layout with sample data, retrieves the saved layout, and validates the layout data.
To run the tests, execute the following command in your custom app's root folder:
bash
$ npm test
Make sure to update the import statements and file paths in the helper function and test file to match your custom app's folder structure.