Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

How to create a repeatable field with multiple rows programmatically (PHP)? #1443

Open
GitHub-Mike opened this issue Nov 26, 2021 · 5 comments

Comments

@GitHub-Mike
Copy link

I have read the documentation, examples and issues in detail, but I cannot find a way to programmatically (PHP) create a repeatable field with multiple rows.

I would like to create a TOC with shortened link texts. I get the original texts from the DB. I want to store the shortened link texts as meta data (one field per page) in the DB.

I only need one field with one row per heading.

I can realise this via JS as "repeatable field". I don't want to generate the lines by click, but programmatically via PHP.

Is there a solution that I have overlooked?

@tw2113
Copy link
Contributor

tw2113 commented Nov 27, 2021

Closest I can think of would be somehow creating some default metadata upon post draft creation that holds an empty array that matches what you want to initially have for structure.

@GitHub-Mike
Copy link
Author

It is an existing WordPress project with many posts. The structure is not complicated as only the H2 headings are used in TOC.

Actually I only need several fields with different id and the name value as array. So like the JS add row functionality does.

@tw2113
Copy link
Contributor

tw2113 commented Nov 29, 2021

Not sure what to suggest for that.

@GitHub-Mike
Copy link
Author

I have now found a solution with 'render_row_cb' callback by looping through there with the headings and inserting the field HTML.

This is a lot of work just to write the value into a name array. It would certainly make sense to build a solution that makes it easier.

Something else:

I write the changed headings with json_encode into an associative array ( ['h2-original' => 'h2-changed', ...] ).

It would be useful if $meta_value was also passed to the hooks "cmb2_save_field" and "cmb2_save_field_{$field_id}". Otherwise this has to be pulled out here: $field->data_to_save[ $field->args( 'id' ) ].

@tw2113
Copy link
Contributor

tw2113 commented Nov 30, 2021

curious how an easier solution for that first part would look like. It's possible the way we potentially implement would be very much like the solution came up with, but as a helper function or similar. More bundled out of box, but less work for the user.

For that last part, we're definitely open to pull requests if you want to work one up.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants