Searched text in search input after submit (PHP) - php

On my site people search for something according on VIN they enter to form. I try to add VIN to session to be able to display it in form after they submit it.
This is how my contructor looks like:
public function __construct( $data = array() ) {
if( isset( $data['vin'] ) ) $this->vin = stripslashes( strip_tags( $data['vin']) );
$this->vin = str_replace("I","1",str_replace("O","0",$this->vin)); // replace i for 1 and o for 0
$_SESSION['vin'] = $this->vin;
}
My HTML site looks like:
<input type="text" maxlength="17" minlength="17" required autofocus name="vin" value="<?php if (isset($_SESSION['vin'])) {echo $_SESSION['vin'];} ?>">
And now the problem:
It display there old vin.
Example:
1. I search for vin XYZ
2. I pres submit and get result for vin XYZ but input bar is empty
3. I search for vin ABC and now after i submit it i get result for ABC but in input i have XYZ vin from session
My idea was that my php site do not reload or something but it should if i get result from submit..
Any idea how can i display current VIN in search input?

Related

How to give dynamic name in array in input field?

I have a form which will have dynamic value and it will check that property id and then save it to the database.
For example in my database there is a table with title having the id=1, type having the id=2, description having the id=3, and after the form is submitted it will check if the field is title or type or description and it will save it in database that is if it is title it will save value of field title with propertyid value 1.
<form method="post" action="something.php">
<input type="text" name="field[][title]" value="edison">
<input type="text" name="field[][type]" value="book">
<input type="text" name="field[][description]" value="some description">
</form>
it is not inputting normal array in php with using foreach, I am not understanding how to get the value inside the index of the array to check with the sql database, that is to check if the field[][title]" then title has id 1 and if the field is field[][description]" it will check the sql for the property id of description that is 3
You need to look at it in reverse.
You first need to query your database so that you have a mapping of which field associates with which ID.
Then, when your information is posted, you can iterate over that mapping, detect if they have been posted, and use them accordingly:
$mapping = loadFieldNamesToFieldId();
/*
mapping should look something like:
$mapping = [
'title' => 1,
'type' => 2
];
*/
foreach ($_POST as $field_name => $field_value) {
if (isset($mapping[$field_name]]) {
$id = $mapping[$field_name];
// at this point you know that the user submitted a field which
// had $field_value, and which ID it relates to in your database
}
}
At which point you can just format your form as so:
<input type="text" name="title" value="edison">
I found this answer and thought of posting this as this relates to the answer
foreach ($_POST as $param_name => $param_val)
{
echo "Param: $param_name; Value: $param_val<br />\n";
}

Setting customer user data with CRUD object in Woocommerce

I'm trying to set a new value for the first_name for a user on woocommerce, i want to do this using the 'CRUD Objects in 3.0' present in the last documentation of woocommerce 3.0.
Só i'm definig the variable:
$wc_current_user = WC()->customer;
This return an instance of the class WC_Customer with has an array of $data with data about customer like $first_name, $last_name, $email, $billing_address array and so on...
i'm trying to rewrite the edit-account.php form and want to submit this data on this object, he provide the getters and setters to do this, but seems the setter ins't working, he is not saiving the data.
I'm doing this:
I have a form with takes the first name from the user, this is working fine, i'm using the ->get_first_name and is working fine.
<form class="woocommerce-account-information" action="" method="post">
<label>First Name</label>
<input type="text" name="first_name" value="<?php echo
$wc_current_user->get_first_name()?>"/>
<button type="submit">SAVE</button>
</form>
The Problema is here, when i try to submit this data using a setter, which in this case is 'object -> set_first_name' and 'object->save()', nothing happens, someone can help me?
Here is my code:
if( isset($_POST['first_name'] ) ){
$wc_current_user->set_first_name($_POST['first_name']);
$wc_current_user->save();
}
//THIS ^ DON'T WORK, do you know what is wrong?
I'm interested in knowing both the old and the new method, if anyone can help me, it will be a great help. Thank you!
You're using the correct method to set the user's first name.
set_first_name() won't permanently save a value on its own. When you've set all the properties you wish to update you need to call the save() method.
if ( isset( $_POST['first_name'] ) ) {
$wc_current_user->set_first_name( $_POST['first_name'] );
$wc_current_user->save();
}
https://woocommerce.wordpress.com/2016/10/27/the-new-crud-classes-in-woocommerce-2-7/
https://github.com/woocommerce/woocommerce/wiki/CRUD-Objects-in-3.0
I find a solution for this problem, when you use object like this you need to use the $object-save() method that Nathan has said plusthe $object->apply_changes(); to submit replace the data on data-base:
public function apply_changes() {
$this->data = array_replace_recursive( $this->data, $this->changes );
$this->changes = array();
}
My working code looks like this:
$wc_current_user = WC()->customer;
if ( isset($_POST['first_name']) ) {
$wc_current_user->set_first_name($_POST['first_name']);
$wc_current_user->save();
$wc_current_user->apply_changes();
}

Wordpress set value from input field as comment author for logged in users

I have a shared account, lets call it "marketing".
Now I have three people using this account named Anna, Ben and Max.
When someone logs into this account and wants to type a comment with their name, it always shows the name "marketing" as author. How can I change this so that I put a name in my input field and I get the value from this as my comment author. In my comments.php I do not check if the user is logged on and call it here:
<input type="text" name="author" id="author" value="<?php echo $comment_author; ?>" size="22" tabindex="2"/>
I tried to make following in my functions.php:
function change_author( $commentdata ) {
if ( $commentdata['user_ID'] == 2 ) { // User ID for Marketing
$commentdata['user_ID'] = 0;
$commentdata['comment_author'] = '';
}
return $commentdata;
}
add_filter( 'preprocess_comment' , 'change_author' );
In this case my comment_author will always be Anonymous and also if I set it to NULL.
When i give the variable a value $commentdata['comment_author'] = 'test';
I get "test" as my comment_author but as I said, I would like to have the value I set in my input field. It works for not logged in users very well so I thought there might be a trick for logged in users as well.
In phpMyAdmin I checked for the entries in the database and it is giving me the right values for ID etc. But it also empties the comment_author field which results in an anonymous author.
I really hope that somebody can give me the right hint to accomplish this task.
https://wordpress.org/plugins/allow-multiple-accounts/ this plugin might help you, you can have multiple accounts under one account.
Goddamit, I didn't know that this was so f***ing easy.
function change_author( $commentdata ) {
if ( $commentdata['user_ID'] == 2 ) {
$commentdata['user_ID'] = 0;
$commentdata['comment_author'] = $_POST['author'];
$commentdata['comment_author_email'] = '';
$commentdata['comment_author_url'] = '';
}
return $commentdata;
}
add_filter( 'preprocess_comment' , 'change_author' );
I think this would work also with != 0 instead of == 2.
This is just a solution for my custom theme but I think it would also work with
$commentdata['comment_author_email'] = $_POST['mail'];
$commentdata['comment_author_url'] = $_POST['url'];
Note: the value in $_POST[] is either the name or the ID from the
input field. Didn't test everything because name and ID have the same
value in my theme.
Tested it a few times local and it worked very well!

insert into wp database not working [duplicate]

I have the following form on a wordpress template page. I'm getting a 404 error each time i submit the form but I'm not using any of the reserved workpress parameter names in the form.
<?php
/**
* Template Name: Registration Template
*/
if(isset($_POST['form-submitted']))
{
if(trim($_POST['runner']) === '') {
$runnerError = 'Please enter runner runner.';
$hasError = true;
} else {
$runner = trim($_POST['runner']);
}
if(trim($_POST['racenumber']) === '') {
$numberError = 'Please enter a race number.';
$hasError = true;
} else {
$racenumber = trim($_POST['racenumber']);
}
$race = trim($_POST['race']);
error_log($race.' '.$runner.' '.$racenumber);
$registrationSubmitted = true;
}
get_header();
echo "<pre>GET "; print_r($_GET); echo "</pre>";
echo "<pre>POST "; print_r($_POST); echo "</pre>";
?>
<div id="container">
<?php
if(isset($registrationSubmitted) && $registrationSubmitted == true)
{
echo '<div class="thanks"><p>The runner has been registered.</p></div>';
}
else
{
$races = // magic array
$selectRaces = '<select name="race" id="race">';
foreach($races as $racez)
{
$selectRaces .= sprintf('<option value=%d>%s</option>',$race->id,$race->name);
}
$selectRaces .= '</select>';
echo apply_filters('the_content','
<form action="'.get_permalink().'" id="form" method="POST">
[one_half last="no"]
<b>Race Details</b><br/>
RaceNumber<input type="text" name="racenumber" id="racenumber"/><br/>
Race'.$selectRaces.'<br/>
[/one_half]
[one_half last="yes"]
<b>Runner Details</b><br/>
ID<input type="text" name="runner" id="runner"/><br/>
Firstname<input type="text" name="first" id="first"/><br/>
Surname<input type="text" name="last" id="last"/><br/>
Gender<input type="text" name="gender" id="gender"/><br/>
DOB<input type="text" name="dob" id="dob"/><br/>
Standard<input type="text" name="standard" id="standard"/><br/>
Company<input type="text" name="company" id="company"/><br/>
[/one_half]
<input type="submit" value="Register Runner"/>
<input type="hidden" name="form-submitted" id="bhaa-submitted" value="true" />
</form>');
}
echo '</div>';
?>
<?php get_footer(); ?>
I've customised my 404 page to dump the $_POST values so i'm sure the parameter values are being submitted.
[racenumber] => 5
[race] => 2596
[runner] => 5
[first] =>
[last] =>
[gender] =>
[dob] =>
[standard] =>
[company] =>
[form-submitted] => true
Can anyone explain my the logic in my 'isset($_POST['form-submitted'])' is not being exercised?
The generated html
<form action="http://localhost/registration/" id="form" method="POST">
<div class="one_half">
<b>Race Details</b><br><br>
RaceNumber<input name="number" id="number" type="text"><br><br>
Race<br>
<select name="race" id="race">
<option value="2596" id="2596">4-Mile-M</option>
<option value="2595" id="2595">2-Mile-W</option>
</select>
EDIT
I've changed the code where is set the values of the select dropdown to use an incrementing int value rather than using sprintf to map a string value to an int value. When the first element is selected the form submits, if the second option is picked i get a 404!
$races = // magic array
$selectRaces = '<select name="race" id="race">';
$i=0;
foreach($races as $racez)
{
$selectRaces .= sprintf('<option value=%d>%s</option>',$i++,$race->name);
}
Problem is that WordPress have some words reserved and it will throw that error when submitting forms:
Some of the words that I found myself and surfing the web are:
Custom post type names
taxonomy names
"name"
"day"
"month"
"year"
"category"
"title"
So be careful when creating a a custom form and try to name your inputs with some prefix. In my case, I had a custom post type called "history" and I was naming the input the same way.
Have you tried resetting your permalinks?
Could be an issue there somewhere.
It doesn't seem or look like the issue is isset($_POST['form-submitted'])'
It's possible your page name is being used another plugin.
WordPress's get_permalink() is generating a URL that is being injected into your output HTML's form tag.
If you look at the HTML source, as it appears in your browser (eg right-click, view-source or right-click, inspect element), find this:
<form action='some_url_here' ...>.
I would expect that this URL should probably be the same as the one that you're currently browsing... ie it tells the browser to send the details back to that same PHP file to process its results.
Type unique Name and ID try this form
<form action="'.get_permalink().'" id="form" method="POST">
[one_half last="no"]
<b>Race Details</b><br/>
RaceNumber<input type="text" name="racenumber" id="racenumber"/><br/>
Race'.$selectRaces.'<br/>
[/one_half]
[one_half last="yes"]
<b>Runner Details</b><br/>
ID<input type="text" name="runner_id" id="runner_id"/><br/>
Firstname<input type="text" name="runner_first" id="runner_first"/><br/>
Surname<input type="text" name="runner_last" id="runner_last"/><br/>
Gender<input type="text" name="runner_gender" id="runner_gender"/><br/>
DOB<input type="text" name="runner_dob" id="runner_dob"/><br/>
Standard<input type="text" name="runner_standard" id="runner_standard"/><br/>
Company<input type="text" name="runner_company" id="runner_company"/><br/>
[/one_half]
<input type="submit" value="Register Runner"/>
<input type="hidden" name="form-submitted" id="bhaa-submitted" value="true" />
</form>
Here is what seems to be a full list:
attachment
attachment_id
author
author_name
calendar
cat
category
category__and
category__in
category__not_in
category_name
comments_per_page
comments_popup
custom
customize_messenger_channel
customized
cpage
day
debug
embed
error
exact
feed
hour
link_category
m
minute
monthnum
more
name
nav_menu
nonce
nopaging
offset
order
orderby
p
page
page_id
paged
pagename
pb
perm
post
post__in
post__not_in
post_format
post_mime_type
post_status
post_tag
post_type
posts
posts_per_archive_page
posts_per_page
preview
robots
s
search
second
sentence
showposts
static
subpost
subpost_id
tag
tag__and
tag__in
tag__not_in
tag_id
tag_slug__and
tag_slug__in
taxonomy
tb
term
terms
theme
title
type
w
withcomments
withoutcomments
year
I had the same issue but I found when I submitted empty input fields (without any value in input field) that's working fine then I leave few input fields remain empty and place value in others which was also working fine.
That's means the issue was one of my input field not in wordpress or
in my code.
You can't use this variables in POST FORM
_ajax_nonce
_page
_per_page
_signup_form
_total
_url
_wp_http_referer
_wp_original_http_referer
_wp_unfiltered_html_comment
_wpnonce
_wpnonce-custom-header-upload
aa
action
action2
active_post_lock
add_new
add_new_users
addmeta
admin_bar_front
admin_color
admin_email
admin_password
admin_password2
ajax
align
allblogs
allusers
alt
approve_parent
approved
attachment
attachment_id
attachments
auth_cookie
author
author_name
autocomplete_type
auto_draft
auto-add-pages
autosave
background-attachment
background-color
background-position-x
background-repeat
banned_email_domains
blog
blog_name
blog_public
blog_upload_space
blogname
bulk_edit
c
calendar
cat
category_base
category_name
catslist
changeit
changes
charset
checkbox
checked
clear-recent-list
closed
comment
comment_approved
comment_author
comment_author_email
comment_author_url
comment_content
comment_date
comment_ID
comment_parent
comment_post_ID
comment_shortcuts
comment_status
comments_listing
comments_popup
confirmdelete
connection_type
content
context
cpage
create-new-attachment
createuser
customize_messenger_channel
customized
customlink-tab
date
date_format
date_format_custom
day
default-header
delete
delete_all
delete_all2
delete_comments
delete_option
delete_tags
delete_widget
deletebookmarks
deletecomment
deleted
deletemeta
deletepost
description
detached
dismiss
display_name
do
edit_date
email
error
exact
excerpt
features
feed
fetch
fheight
file
fileupload_maxk
filter
find_detached
first_comment
first_comment_author
first_comment_url
first_name
first_page
first_post
found_post_id
fwidth
global_terms_enabled
GLOBALS
gmt_offset
guid
height
hh
hidden
hidden_aa
hidden_jj
hidden_mm
hidden_mn
hidden_hh
history
hostname
hour
html-upload
id
ID
ids
id_base
illegal_names
insert-gallery
insertonlybutton
interim-login
item-object
item-type
jj
json
json_data
key
last_name
limited_email_domains
link_id
link_image
link_name
link_rss
link_url
link_visible
linkcheck
locale
locked
log
logged_in_cookie
m
media
media_type
menu
menu_items
menu-item
menu-item-attr-title
menu-item-classes
menu-item-db-id
menu-item-description
menu-item-object
menu-item-object-id
menu-item-parent-id
menu-item-position
menu-item-target
menu-item-title
menu-item-type
menu-item-url
menu-item-xfn
menu-locations
menu-name
message
meta
metakeyinput
metakeyselect
metavalue
minute
mm
mn
mode
monthnum
more
move
multi_number
name
nav-menu-locations
new
new_role
new_slug
new_title
newcat
newcomment_author
newcomment_author_email
newcomment_author_url
newcontent
newuser
nickname
no_placeholder
noapi
noconfirmation
noredir
number
offset
oitar
option
option_page
order
orderby
p
pb
page
page_columns
page_id
page_options
paged
pagegen_timestamp
pagename
parent_id
pass1
pass2
password
permalink_structure
photo_description
photo_src
phperror
ping_status
plugin
plugin_status
pointer
position
post
post_category
post_data
post_format
post_ID
post_id
post_mime_type
post_password
post_status
post_title
post_type
post_view
postid
posts
preview
primary_blog
private_key
ps
public_key
publish
pwd
query
reassign_user
reauth
redirect
redirect_to
ref
referredby
registration
registrationnotification
rememberme
remove-background
removeheader
removewidget
reset-background
resetheader
review
rich_editing
robots
role
s
same
save
savewidget
savewidgets
screen
scrollto
search
second
section
selectall
selection
send
send_password
sentence
short
show_sticky
sidebar
sidebars
signup_for
signup_form_id
site_id
site_name
sitename
size
skip-cropping
spam
spammed
src
ss
stage
start
static
status
sticky
subdomain_install
submit
subpost
subpost_id
super_admin
tab
tag
tag_ID
tag-name
tag_base
tags_input
tax
tax_input
tag-name
target
taxonomy
tb
term
text-color
the-widget-id
theme
theme_status
thumb
timezone_string
time_format
time_format_custom
title
thumbnail_id
trash
trashed
type
undismiss
unspam
unspammed
untrash
untrashed
url
update_home_url
updated
upgrade
upload_filetypes
upload_space_check_disabled
use_ssl
user
user_id
user_login
user_name
username
users
verify-delete
version
visibility
visible
w
weblog_title
welcome_email
welcome_user_email
widget_id
widget_number
widget-id
widget-recent-comments
widget-rss
width
withcomments
withoutcomments
wp_customize
wp_http_referer
wp_screen_options
wp-preview
WPLANG
x1
y1
year

Symfony - Several form on the same page -> ID issue

I have an issue while displaying several forms of the same model on the same page.
The problem is that with the NameFormat, the fields have the same ID :
$this->widgetSchema->setNameFormat('display[%s]');
Will display
<form class="update_display_form" id="update_display_0" action="/iperf/web/frontend_dev.php/update_display" method="post">
<input type="checkbox" name="display[displayed]" checked="checked" id="display_displayed" />
<label for="display_displayed">test</label>
</form>
<form class="update_display_form" id="update_display_1" action="/iperf/web/frontend_dev.php/update_display" method="post">
<input type="checkbox" name="display[displayed]" checked="checked" id="display_displayed" />
<label for="display_displayed">truc</label>
</form>
And if you click on the second label, it will activate the first checkbox
So I thought I could use the object id to make them unique :
$this->widgetSchema->setNameFormat('display'.$this->getObject()->getId().'[%s]');
But then I can not process the request, since I don't know the name of the parameters.
The best option I found was to set an ID :
$this->widgetSchema['displayed']->setAttributes(array("id" => "display".$this->getObject()->getId() ));
but then I totally loose the connections between the label and the checkbox.
The problem would be solved if I could change the "for" attribute of my label. Does somebody know how to do that ? Or any other option ?
Here's an idea... push a variable to the form class from your action for setting a different name format dynamically:
In your action:
$this->form_A = new displayForm(array(),array('form_id' = 'A')); // pass a form id
$this->form_B = new displayForm(array(),array('form_id' = 'B'));
$this->form_C = new displayForm(array(),array('form_id' = 'C'));
In your form class:
$form_id = $this->getOption('form_id'); // get the passed value
$this->widgetSchema->setNameFormat('display'.$form_id.'[%s]'); // stick it into the name
It's ugly but I'm sure you can come up with something cleaner...
Conflicting inter-form checkbox/label interactions is caused by tag's id/for attributes not by their name attributes.
So there is no need to modify form's widget name format and thus having problem reading submitted data from request object (either by passing request key as form url parameter/hidden input or by looping all form name combinations created in the layout for each form and finding a matching one).
sfForm class has sfWidgetFormSchema::setIdFormat() method for that.
// Creating form instances
$formA = new sfForm();
$formA->getWidgetSchema()->setIdFormat( '%s1' );
$formA->getWidgetSchema()->setNameFormat( 'display' );
... // configure the form
$formB = new sfForm();
$formB->getWidgetSchema()->setIdFormat( '%s2' );
$formB->getWidgetSchema()->setNameFormat( 'display' );
... // configure the form
$formC = new sfForm();
$formC->getWidgetSchema()->setIdFormat( '%s3' );
$formC->getWidgetSchema()->setNameFormat( 'display' );
... // configure the form
// Processing a request data
$form = new sfForm();
... // configure the form
$_formNameRequestKey = $form->getName();
if( $request->hasParameter( $_formNameRequestKey ) ) {
$form->bind( $request->getParameter( $_formNameRequestKey ) );
}
... or just ...
if( $request->hasParameter( 'display' ) ) {
$form->bind( $request->getParameter( 'display' ) );
}

Categories