html - Display user inputs in textarea and format as array in database PHP
Get the solution ↓↓↓I've created a custom options page for my WordPress theme and have a textarea for users to add options that will be appended to an array in another file. User input is successfully added to the appropriate location in the database, but it is being stored as a single string. I would like for the user to be able to enter one option on each line and have the inputs saved as an array with each line being saved as an element in the array.
for example:
Textarea user input:
'my option1'
'my option2'
'my option3'
is stored as:
a:1:{s:24:"my_textarea_field_0";s:34:"my option1
my option2
my option3";}
I would like for it to be stored as an array: {"my option1", "my option2", "my option3"}
Also, the text entered into the textarea is saved to the database but is not displayed in the textarea after the submit button is pressed. I would like for the user's input the be added to the database as an array and continue to be displayed in the textarea after it has been submitted.
Here is the relevant code:
function my_textarea_field_0_render() {
$this->$options = get_option('my_settings');
?>
<p style="margin: .25em 0 .5em!important; display: inline-block;">
<label for="my_settings[my_textarea_field_0]">
Lorem ipsum dolor sit amet.</label>
</p>
<p>
<textarea cols='145' rows='8' name='my_settings[my_textarea_field_0]'><?php echo $options['my_textarea_field_0'];?></textarea>
</p>
<?php
add_option('my_settings', '$options');
}
I've spent a while searching for solutions and tinkering with the code, but I haven't been able to figure it out.
Answer
Solution:
- To make array from value of textarea, use
explode
function. Maybe this sample code is useful for you.
$arrTextarea = explode("\n", str_replace("\r", "", $valTextarea));
- You should use only
php
code in function.
function my_textarea_field_0_render() {
$this->$options = get_option('my_settings');
$html = `
<p style="margin: .25em 0 .5em!important; display: inline-block;">
<label for="my_settings[my_textarea_field_0]">
Lorem ipsum dolor sit amet.</label>
</p>
<p>
<textarea cols='145' rows='8' name='my_settings[my_textarea_field_0]'>` .
$options['my_textarea_field_0'] .
`</textarea>
</p>`;
add_option('my_settings', '$options'); // I didn't understand what is $options.
}
Share solution ↓
Additional Information:
Link To Answer People are also looking for solutions of the problem: trying to access array offset on value of type bool
Didn't find the answer?
Our community is visited by hundreds of web development professionals every day. Ask your question and get a quick answer for free.
Similar questions
Find the answer in similar questions on our website.
Write quick answer
Do you know the answer to this question? Write a quick response to it. With your help, we will make our community stronger.