admin管理员组

文章数量:1278690

I am trying to create a plugin that will add a custom block in Gutenberg that will display a div with a combination 3 links on the frontend, based on the options that that I choose in the editor. In other words, if I have L1 (link 1), L2 (link 2) and L3 (link 3), I want to be able to choose in the editor which combination of the 3 links (L1 only, L2 only, L3 only, L1 and L2, L1 and L3, ..., L1 and L2 and L3) I will display.

My idea is to use 3 checkboxes (one for each link) to select which I want to display.

So far, I have managed to create one checkbox in my block and to extract its status (checked or unchecked) as a boolean but I am struggling when the number of checkboxes increases. Here is my code:

var el = wp.element.createElement;

wp.blocks.registerBlockType('custom-blocks/interactive-btn', {

   title: 'Interactive button',

   category: 'formatting',

   attributes: { // Data stored by block
      links: { type: 'boolean', source: 'attribute', selector: 'input', attribute: 'checked' } 
   },

   edit: function( props ) {
      function updateLinks( event ) {
         props.setAttributes( { links: event.target.checked } );
         //console.log( props.attributes.links );
      }

      return(el('form',
         {
         onChange:updateLinks,
         value: props.attributes.links
         },
         el('input', { type: 'checkbox', name:'link1', value: 'link1' }),
         el('label', { for: "link1" }, "Link 1" ),   
         )
      );
   },

   save: function( props ) { 
   }
}
);

It works, but I when I increase the number of checkboxes and try to stores their respective statuses in an array, I cannot get my code to work. Any help would be appreciated!

EDIT As requested, here is the solution I tried with 2 checkboxes:

var el = wp.element.createElement;

wp.blocks.registerBlockType('custom-blocks/interactive-btn', {

   title: 'Interactive button',

   category: 'formatting',

   attributes: { // Data stored by block
      links: { type: 'array', source: 'attribute', selector: 'input', attribute: 'checked' } 
   },

   edit: function( props ) { 
      function updateLinks( event ) {
         props.setAttributes( { links: event.target.checked } );
         //console.log( props.attributes.links );
      }

      return(el('form',
         {
         onChange:updateLinks,
         value: props.attributes.links
         },
         el('input', { type: 'checkbox', name:'link1', value: 'link1' }),
         el('label', { for: "link1" }, "Link 1" ),   
         el('input', { type: 'checkbox', name:'link2', value: 'link2' }),
         el('label', { for: "link2" }, "Link 2" ),   
         )
      );
   },

   save: function( props ) {
   }
}
);

I am sure what I did is not right, but I don't know how to specify my block attributes so I have the two boolean variables within a single array... Any ideas?

本文标签: pluginsHow to create a custom block in Gutenberg with multiple checkboxes