givanz / VvvebJs

Drag and drop page builder library written in vanilla javascript without dependencies or build tools.
https://www.vvveb.com/vvvebjs/editor.html
Apache License 2.0
7.31k stars 1.66k forks source link

Adding a component using PHP and dynamically changing its attributes from the database #334

Open Duynguyen0897 opened 9 months ago

Duynguyen0897 commented 9 months ago

Hi, How to dynamically add a new component/ section/ block using PHP Ajax and allow selecting properties from the database. For example, I need to add a component that displays a list of news articles from a specific news category. When the category changes, the component needs to be updated, and if possible, how to store these properties in the database instead of static HTML to increase the flexibility of the component when the news data changes.

givanz commented 9 months ago

Hi

Components can have a onChange(element, property, value, input) https://github.com/givanz/VvvebJs/wiki/Components#component-definition that is triggered on any property change.

You can use the event to send any new parameter change through ajax call and get the new html from the server and update the page.

If you want to save the properties to database you can use the same ajax call to save the properties as json and set a unique id to the html element to link the properties to the element.

This approach is used in Vvveb CMS dynamic/server components https://github.com/givanz/Vvveb/blob/master/public/js/vvvebjs/components/server-component.js#L95 but properties are not saved to database but as html attributes like data- this is less complex and much easier to maintain.

The html attributes are then read with php dom document and the proper posts are rendered based on the properties value.

<div class="container" data-v-component-posts="posts-1" data-v-limit="3" data-v-image_size="medium">
</div>