WooCommerce - Add Country/State Select Fields to Registration Form? - function

I've read through, and followed the following tutorial How to add custom fields in user registration on the "My Account" page and successfully added several custom fields to the registration form on the My Account page (seen when users are logged out).
I'd like to add billing country/state as select fields if the shop owner has defined them. (i.e. If the shop only services Canada, load only Provinces).
Unfortunately the tutorial doesn't cover select fields, just basic text fields. I did find another thread that lists how to add countries but it's all countries, not the ones specified by the shop owner.
Anyone have any further insight in loading Countries/Provinces/States that are set by the shop owner? So far I've got the following:
/**
* Add new register fields for WooCommerce registration.
*
* #return string Register fields HTML.
*/
function wooc_extra_register_fields() {
$countries_obj = new WC_Countries();
$countries = $countries_obj->__get('countries');
?>
<fieldset>
<legend><h3>Address</h3></legend>
<p>Please provide the main contact address for this account.</p>
<p class="form-row form-row-wide">
<label for="reg_billing_address_1"><?php _e( 'Address', 'woocommerce' ); ?> <span class="required">*</span></label>
<input type="text" class="input-text" name="billing_address_1" id="reg_billing_address_1" placeholder="Street/P.O Box address" value="<?php if ( ! empty( $_POST['billing_address_1'] ) ) esc_attr_e( $_POST['billing_address_1'] ); ?>" />
</p>
<div class="clear"></div>
<p class="form-row form-row-wide">
<label for="reg_billing_address_2"><?php _e( 'Address Line 2', 'woocommerce' ); ?></label>
<input type="text" class="input-text" name="billing_address_2" id="reg_billing_address_2" placeholder="Apartment, suite, unit etc. (optional)" value="<?php if ( ! empty( $_POST['billing_address_2'] ) ) esc_attr_e( $_POST['billing_address_2'] ); ?>" />
</p>
<div class="clear"></div>
<p class="form-row form-row-wide">
<label for="reg_billing_city"><?php _e( 'Town/City', 'woocommerce' ); ?> <span class="required">*</span></label>
<input type="text" class="input-text" name="billing_city" id="reg_billing_city" value="<?php if ( ! empty( $_POST['billing_city'] ) ) esc_attr_e( $_POST['billing_city'] ); ?>" />
</p>
<div class="clear"></div>
<p class="form-row form-row-wide">
<label for="reg_billing_postcode"><?php _e( 'Postal Code', 'woocommerce' ); ?></label>
<input type="text" class="input-text" name="billing_postcode" id="reg_billing_postcode" value="<?php if ( ! empty( $_POST['billing_postcode'] ) ) esc_attr_e( $_POST['billing_postcode'] ); ?>" />
</p>
<div class="clear"></div>
<p class="form-row form-row-wide">
<label for="reg_billing_country"><?php _e( 'Country', 'woocommerce' ); ?> <span class="required">*</span></label>
<select class="country_select" name="billing_country" id="reg_billing_country">
<?php foreach ($countries as $key => $value): ?>
<option value="<?php echo $key?>"><?php echo $value?></option>
<?php endforeach; ?>
</select>
</p>
</fieldset>
<?php
}
add_action( 'woocommerce_register_form_start', 'wooc_extra_register_fields' );

To add Woocommerce Country/State fields in some other form use the following code in template:
<?php
$field = [
'type' => 'country',
'label' => 'Country',
'required' => 1,
'class' => ['address-field']
];
woocommerce_form_field( 'billing_country', $field, '' );
$field = [
'type' => 'state',
'label' => 'State',
'required' => 1,
'class' => ['address-field'],
'validate' => ['state']
];
woocommerce_form_field( 'billing_state', $field, '' );
?>
To tie the Country field selection with State field options put these fields into some container with class woocommerce-billing-fields AND include woocommerce country-select.js at page with the form:
<?php
$handle = 'wc-country-select';
wp_enqueue_script($handle, get_site_url().'/wp-content/plugins/woocommerce/assets/js/frontend/country-select.min.js', array('jquery'), true);
?>

Maybe it's too late but :
Instead of :
<p class="form-row form-row-wide">
<label for="reg_billing_country"><?php _e( 'Country', 'woocommerce' ); ?> <span class="required">*</span></label>
<select class="country_select" name="billing_country" id="reg_billing_country">
<?php foreach ($countries as $key => $value): ?>
<option value="<?php echo $key?>"><?php echo $value?></option>
<?php endforeach; ?>
</select>
</p>
place :
<?php
$countries_obj = new WC_Countries();
$countries = $countries_obj->get_allowed_countries();
woocommerce_form_field('billing_country', array(
'type' => 'select',
'class' => array( 'chzn-drop' ),
'label' => __('Pays'),
'placeholder' => __('Sélectionnez un pays'),
'options' => $countries
)
); ?>
You'll get a select dropdown of allowed countries
If you want a list of all countries, replace "get_allowed_countries();" by "__get('countries');"
Source
States are treated in this source

Related

Input type file activeform Yii2 generate another input type hidden

I have some problem when using activeform type file. When i try to send my input in registration controller the validation from model always return it false because there is input type file that empty. After i checking from html inspect elements, it turns out that the form I created on the register page generates a new input on it with the type hidden and the same name. I still can't understand why it can generate another input type hidden and input post in controller read from that input type hidden
this is my activeform:
<?php $form = ActiveForm::begin(['id' => 'form-signup', 'action' => '/site/register/userregister', 'options' => ['enctype' => 'multipart/form-data'], 'method' => 'post' ]); ?>
<?= $form->field($model,'email')->textInput()->input('email', ['placeholder' => "Email"])->label(false) ?>
<?= $form->field($model,'photofile',
['options' => ['class' => 'form-group']])
->fileInput([])
->label('Photo file<br/><span style="font-size:12px;font-style:italic;">(Max. size 1 MB, Allowed type: .jpg, .jpeg, .png)</span>') ?>
<?= $form->field($model,'resumefile',
['options' => ['class' => 'form-group']])
->fileInput([])
->label('Resume file<br/><span style="font-size:12px;font-style:italic;">(Max. size 1 MB, Allowed type: .doc, .docx, .pdf)') ?>
<div class="form-group">
<?= Html::submitButton('Sign Up', ['class' => 'btn btn-sign', 'type' => 'submit']) ?>
</div>
<h6 class="mt-3">Have an account? <a class="font-weight-bold" href="<?= Url::to(['login/userlogin']) ?>">Sign In</a></h6>
<?php ActiveForm::end(); ?>
this my controller :
public function actionUserregister()
{
$model = new SignupModel();
if (Yii::$app->request->isPost) {
$input = Yii::$app->request->post('SignupModel');
echo "<pre>";var_dump($input);exit;
}
}
this is function in to validate rule input:
public function rules()
{
return [
['photofile', 'required'],
['photofile', 'file', 'extensions' => 'jpg,jpeg,png', 'maxSize' => 1024 * 1024 * 1],
['resumefile', 'required'],
['resumefile', 'file', 'extensions' => 'pdf,doc,docx', 'maxSize' => 1024 * 1024 * 1 ],
];
}
and this is what i see in inspect elements:
<div class="form-group field-signupmodel-photofile required">
<label class="control-label" for="signupmodel-photofile">Photo file</label>
<input type="hidden" name="SignupModel[photofile]" value> //here is the problem
<input type="file" id="signupmodel-photofile" name="SignupModel[photofile]" aria-required="true">
<p class="help-block help-block-error"></p>
</div>
<div class="form-group field-signupmodel-resumefile required">
<label class="control-label" for="signupmodel-resumefile">Resume file</label>
<input type="hidden" name="SignupModel[resumefile]" value> //here is the problem
<input type="file" id="signupmodel-resumefile" name="SignupModel[resumefile]" aria-required="true">
<p class="help-block help-block-error"></p>
</div>
what's wrong with my code above?

insert form_dropdown data into mysql database in codeigniter

I am new in codeigniter and trying to insert form_dropdown data into database, But i am unabl to insert selected option into database.
This is my model:
public function insertUser()
{
$data1 = array(
'id'=>$this->input->post('id'),
'full_name'=>$this->input->post('full_name'),
'email'=>$this->input->post('email'),
'contact_no'=>$this->input->post('contact_no'),
'role'=>$this->roles[0],
'status'=>$this->status[0]
);
$this->db->insert('users',$data1);
$data2['user_id']=$this->db->insert_id();
$data2 = array(
'type_of_paper'=>$this->input->post('type_of_paper'),
'deadline'=>$this->input->post('deadline'),
'acadmic_level'=>$this->input->post('acadmic_level'),
'quality'=>$this->input->post('quality'),
'noofpage'=>$this->input->post('noofpage'),
'subject_area'=>$this->input->post('subject_area')
);
$this->db->insert('orders',$data2);
return $this->db->insert_id();
}
This is my controller:
public function order()
{
$data['title']='Order';
$data['page']='order';
$data['type_of_paper'] = $this->writer_model->getTypeOfPaper();
$data['deadline'] = $this->writer_model->getDeadline();
$data['prices'] = $this->writer_model->getPrice();
$data['acadmic_level']=$this->writer_model->getAcadmicLevel();
$data['quality']=$this->writer_model->getQuality();
$data['subject_area']=$this->writer_model->getSubjectArea();
$data['currencies']=$this->writer_model->getCurrency();
$this->form_validation->set_rules('full_name', 'Full Name', 'trim|required|min_length[5]|max_length[50]|is_unique[users.full_name]',
array(
'required' => 'You have not provided %s.',
'is_unique' => 'This %s already exists.'
));
$this->form_validation->set_rules('email', 'Email', 'trim|required|valid_email|is_unique[users.email]',
array(
'required' => 'You have not provided correct %s.',
'is_unique' => 'This %s already exists.'
));
$this->form_validation->set_rules('contact_no', 'Contact No', 'trim|required');
$this->form_validation->set_rules('type_of_paper', 'Type Of Paper', 'trim|required');
$this->form_validation->set_rules('deadline', 'Deadline', 'trim|required');
$this->form_validation->set_rules('acadmic_level', 'Acadmic Level', 'trim|required');
$this->form_validation->set_rules('quality', 'Quality', 'trim|required');
$this->form_validation->set_rules('noofpage', 'No Of Pages', 'trim|required');
$this->form_validation->set_rules('subject_area', 'Subject Area', 'trim|required');
if ($this->form_validation->run() == FALSE)
{
$this->load->view('header', $data);
$this->load->view('navbar', $data);
$this->load->view('order', $data);
$this->load->view('footer', $data);
}else
{
if($this->user_model->isDuplicate($this->input->post('email')))
{
$this->session->set_flashdata('flash_message', 'User email already exists');
redirect(site_url().'/home/login');
}else
{
$config=array(
'protocol' => 'smtp',
'smtp_host' => 'ssl://smtp.googlemail.com',
'smtp_port' => 465,
'smtp_user' => '',
'smtp_pass' => '',
'mailtype' => 'html'
);
$clean = $this->security->xss_clean($this->input->post(NULL, TRUE));
$id = $this->user_model->insertUser($clean);
$token = $this->user_model->insertToken($id);
$qstring = $this->base64url_encode($token);
$url = site_url() . '/home/complete/token/' . $qstring;
$link = $url;
$message = '';
$message .= 'You have signed up with our website.
Please click here to verify your email address:'. $link;
$this->load->library('email',$config);
$this->email->set_newline("\r\n");
$this->email->from('','Gourav shukla');
$this->email->to($this->input->post('email'));
$this->email->subject('This is an email Test');
$this->email->message($message);
$this->email->send();
/*if($this->email->send();)
{
echo 'Your email was sent, fool.';
}else
{
show_error($this->email->print_debugger());
}
echo $message; send this in email
exit;*/
};
}
}
This is my view code:
<?php // Change the css classes to suit your needs
$attributes = array('class' => 'form-horizontal', 'id' => 'order_form', 'name' => 'order_form');
echo form_open('/home/order', $attributes); ?>
<h3>Customer Information :</h3>
<?php echo form_input(array('name'=>'full_name', 'id'=> 'full_name', 'placeholder'=>'Full Name', 'class'=>'full_name', 'value' => set_value('full_name'))); ?>
<?php echo form_error('full_name');?>
<?php echo form_input(array('name'=>'email', 'id'=> 'email', 'placeholder'=>'Email', 'class'=>'email', 'value'=> set_value('email'))); ?>
<?php echo form_error('email');?>
<?php echo form_input(array('name'=>'contact_no', 'id'=> 'contact_no', 'placeholder'=>'Contact No', 'class'=>'contact_no', 'value'=> set_value('contact_no'))); ?>
<?php echo form_error('contact_no');?>
<hr />
<h3>Order Pricing :</h3>
<?php $attributes = 'id="type_of_paper" class="form-control"';
echo form_dropdown('type_of_paper', $type_of_paper, set_value('type_of_paper'), $attributes);?>
<?php echo form_error('type_of_paper'); ?>
<?php $attributes = 'id="deadline" class="form-control"';
echo form_dropdown('deadline', $deadline, set_value('deadline'), $attributes); ?>
<?php echo form_error('deadline'); ?>
<select class="form-control" id="acadmic_level" name="acadmic_level" onchange="calculateTotal()">
<option value=""> - Acadmic Level - </option>
<?php foreach($acadmic_level as $row)
{
echo '<option value="'.$row->value.'" id="'.$row->level_name.'">'.$row->level_name.'</option>';
}
?>
</select>
<?php echo form_error('acadmic_level'); ?>
<select class="form-control" name="quality" id="quality" onchange="calculateTotal()">
<option value=""> - Quality - </option>
<?php foreach($quality as $row)
{
echo '<option value="'.$row->q_value.'" id="'.$row->q_type.'">'.$row->q_type.'</option>';
}
?>
</select>
<?php echo form_error('quality'); ?>
<br />
<input type="text" maxlength="150" name="noofpage" id="noofpage" placeholder="No Of Pages" onkeyup="calculateTotal()"/>
<?php $attributes = 'id="price" class="form-control"';
echo form_dropdown('prices', $prices, set_value('prices'), $attributes); ?>
<input id="amount" name="amount" placeholder="Amount in British Pound(£)" type="text" />
<?php echo form_error('noofpage'); ?>
<select class="form-control" name="currency" id="currency" onchange="getCurrency()">
<?php foreach($currencies as $row)
{
echo '<option value="'.$row->rate.'">'.$row->name.'</option>';
}
?>
</select>
<?php echo form_error('currency'); ?><br />
<div id="finalPrice"></div><br />
<div id="totalPrice" name="totalPrice"></div>
<hr />
<h3>Order Information :</h3>
<select class="form-control" id="subject_area" name="subject_area">
<option value=""> - Subject Area - </option>
<?php foreach($subject_area as $row)
{
echo '<option value="'.$row->subject_area.'">'.$row->subject_area.'</option>';
}
?>
</select>
<?php echo form_error('subject_area'); ?>
<?php echo form_input(array('name'=>'required_topic', 'id'=> 'required_topic', 'placeholder'=>'Required Topic', 'class'=>'required_topic', 'value' => set_value('required_topic'))); ?>
<?php echo form_error('required_topic');?><br />
<?php echo "<input type='file' name='userfile' size='20' />"; ?><br />
<?php $data = array('name'=> 'vc_desc','id'=> 'vc_desc','value'=> set_value('vc_desc'),'rows'=> '6','cols'=> '10','placeholder'=>'Detailed Instructions','style'=> 'width:50%; margin-left:100px','class'=> 'form-control');
echo form_textarea($data); ?><br />
<hr />
<h3>Select Payment Method :</h3>
<?php echo form_radio("gender", "Female", NULL, set_radio('gender', 'Female')); ?>Female
<?php echo form_radio("gender", "Male", NULL, set_radio('gender', 'Male')); ?>Male<br />
<input type="checkbox" name="accept_terms_checkbox" value="Accept TOS" /> Accept Terms of Services<br>
<?php echo form_error('accept_terms_checkbox') ?>
<?php echo form_submit(array('value'=>'Place Order', 'class'=>'btn btn-md btn-primary btn-block')); ?>
<?php echo form_close(); ?>
When i am running this code then i am getting this output:
output image
but i want to store option name into database not value from option.
Please fix this problem.
thanks in advance.
what i got from your last two lines and image that is data is inserting into database but values are inserting and you wants to insert names,
if i correct then,
you have to use your names in options value like
<option value="name">name or anything you want</option>
in form_dropdown
$style=array("id"=>"any_id","class"=>"any_class");
$dd_data=array();
$dd_data['']="-select-";
foreach($data as $row) // $data coming from server
{
$dd_data[$row['name']]=$row['name or anything'] // $row['name'] names that you wants to add into database
}
echo form_dropdown('field_name',$dd_data,'',$style);
this code is just an example it is not tested.

Posting HTML form to new wp database table

I'm trying to make a HTML form post the input values to a custom table in the WordPress database. I've managed to get something to show up in a new row, but almost all of my values return N; instead of the value from the form.
Here's the code I have in my page template:
<?php
global $wpdb;
global $current_user;
$userID = $current_user->ID;
$brand = serialize($_POST["brand"]);
$url = serialize($_POST["url"]);
$sector = serialize($_POST["sector"]);
$keywords = serialize($_POST["keywords"]);
if (
'POST' == $_SERVER['REQUEST_METHOD'] && !empty( $_POST['action'] ) && $_POST['action'] == 'updateSearch' ) {
$ufDataUpdate = $wpdb->insert( 'wp_wct3', array(
'date' => current_time('mysql'),
'userid' => $userID,
'brand' => $brand,
'url' => $url,
'sector' => $sector,
'keywords' => $keywords ) );
}
?>
<form method="post">
<label for="brand">Brand/Product Name: </label>
<input type="text" id="brand" placeholder="eg: Spidr" class="clearfix" required />
<label for="website">Website address: </label>
<input type="url" id="url" placeholder="eg: www.spidr.co.uk" class="clearfix" required />
<label for="sector">Market sector: </label>
<input type="text" id="sector" placeholder="eg: Internet Marketing Tools" class="clearfix" required />
<label for="keyword">Keywords/Phrases:<br><span class="orange">(comma separated)</span></label>
<textarea cols="0" rows="8" class="light" id="keywords" required></textarea>
<input type="submit" id="submit" name="submit" class="button-65 mobile-button" value="release the spiders!">
<?php wp_nonce_field( 'updateSearch' ); ?>
<input name="action" type="hidden" id="action" value="updateSearch" />
</form>
Where wp_wct3 is the database name and each item in the array is the name of each column in that table.
I'm not sure if my issue lies in this code, or in the set-up of the database itself. I've used the Wordpress custom tables plugin to make the new table. The brand, url and sector simply use the text definition, while the keywords use enum('0','1').
Anyone have any ideas why the values aren't returning and I'm just getting N; ?
this is my custom-form template.. it works for me
<?php
/**
Template Name: Custom-Form
* The template for displaying all pages.
*
* This is the template that displays all pages by default.
* Please note that this is the WordPress construct of pages
* and that other 'pages' on your WordPress site will use a
* different template.
*
* #package WordPress
* #subpackage Twenty_Twelve
* #since Twenty Twelve 1.0
*/
get_header(); ?>
<div id="primary" class="site-content">
<div id="content" role="main">
<?php
if (!empty($_POST)) {
global $wpdb;
$table = wp_achord;
$data = array(
'name' => $_POST['yourname'],
'chord' => $_POST['chord']
);
$format = array(
'%s',
'%s'
);
$success=$wpdb->insert( $table, $data, $format );
if($success){
echo 'data has been save' ;
}
}
else {
?>
<form method="post">
<input type="text" name="yourname">
<textarea name="chord"></textarea>
<input type="submit">
</form>
<?php } ?>
</div><!-- #content -->
</div><!-- #primary -->
<?php get_footer(); ?>
Figured out the main issue. I'd missed out the name attribute from the form itself, so my PHP wasn't picking up the field values!

I am creating a recent posts widgets for practice but I need help correctly making it so admin can adjust the category displayed

So like I said in the title, I am creating a recent posts widget for practice. It includes different features and the one that I am having problems with it is allowing admin to choose the category they want to display. I currently have it set up so that in the form it has a text field in which the admin can input the category manually but I need it to be such that it has a drop down menu that already has the category there, so the admin can just select it. I am not sure how to do this at all so if I could get some help that would be great. Sorry if I am being vague, I am new to this. I am posting my code below.
<?php
/*
Plugin Name: News Recent Posts Widget
Plugin URI:
Description: A recent post widget with extra functions that allow admin to make changes to certain values
Author: Kevin Ullyott
Version: 1.0
Author URI: http://modmacro.com/
*/
class recentpost extends WP_Widget {
public function __construct() {
parent::WP_Widget(
// or parent::__construct(
false,
'Kevin - Recent Posts Widget',
array(
'description' => __('A recent post widget with extra functions that allow admin to make changes to certain values')
)
);
;
}
public function widget( $args, $instance ) {
extract( $args );
$headline = $instance['headline'];
$category = $instance['category'];
$numberposts = $instance['numberposts'];
$readmore = $instance['readmore'];
echo $before_widget;
echo $before_title;
echo "<p class=\"headline\">$headline</p>";
echo $after_title;
$args = array( 'numberposts' => $numberposts, 'category_name' => $category );
$recent_posts = wp_get_recent_posts( $args );
foreach( $recent_posts as $recent ){
setup_postdata(get_post($recent['ID']));
echo '<a href="' . get_permalink($recent['ID']) . '" title=" '.esc_attr(get_the_title($recent['ID'])).'" >' . get_the_title($recent['ID']).'</a> ';
echo get_the_time('F j, Y', $recent['ID']);
the_excerpt();
}
wp_reset_postdata();
echo $after_widget;
}
public function update( $new_instance, $old_instance ) {
$instance = array();
$instance['headline'] = ( $new_instance['headline'] );
$instance['category'] = ( $new_instance['category'] );
$instance['numberposts'] = ( $new_instance['numberposts'] );
$instance['readmore'] = ( $new_instance['readmore'] );
return $instance;
}
public function form( $instance ) {
$headline = $instance[ 'headline' ];
$category = $instance[ 'category' ];
$numberposts = $instance[ 'numberposts' ];
$readmore = $instance[ 'readmore' ];
?>
<p>
<label for="<?php echo $this->get_field_id( 'headline' ); ?>">
<?php _e( 'Headline:' ); ?>
</label>
<input class="widefat" id="<?php echo $this->get_field_id( 'headline' ); ?>" name="<?php echo $this->get_field_name( 'headline' ); ?>" type="text" value="<?php echo esc_attr( $headline ); ?>" />
</p>
<label for="<?php echo $this->get_field_id( 'category' ); ?>">
<?php _e( 'Category:' ); ?>
</label>
<input class="widefat" id="<?php echo $this->get_field_id( 'category' ); ?>" name="<?php echo $this->get_field_name( 'category' ); ?>" type="text" value="<?php echo esc_attr( $category ); ?>" />
</p>
<label for="<?php echo $this->get_field_id( 'numberposts' ); ?>">
<?php _e( 'Number of posts:' ); ?>
</label>
<input class="widefat" id="<?php echo $this->get_field_id( 'numberposts' ); ?>" name="<?php echo $this->get_field_name( 'numberposts' ); ?>" type="text" value="<?php echo esc_attr( $numberposts ); ?>" />
</p>
<label for="<?php echo $this->get_field_id( 'readmore' ); ?>">
<?php _e( 'Read More:' ); ?>
</label>
<input class="widefat" id="<?php echo $this->get_field_id( 'readmore' ); ?>" name="<?php echo $this->get_field_name( 'readmore' ); ?>" type="text" value="<?php echo esc_attr( $readmore ); ?>" />
</p>
<?php
}
}
add_action( 'widgets_init', create_function('', 'return register_widget("recentpost");') );
?>
The function wp_dropdown_categories will bring in the categories but adding the function alone wont save or retrieve the selected category. You'll need to add the name selected and id arguments. This should work I think:
<?php wp_dropdown_categories(array('name' => $this->get_field_name('category'), 'selected' => $category, 'id' => $this->get_field_id('category'), 'class' => 'widefat')); ?>
I added class widefat as well but its only for presentation. Hope that helps.
The function wp_dropdown_categories displays a dropdown menu that pulls in all of the categories used in the site. Here is the documentation on it: http://codex.wordpress.org/Function_Reference/wp_dropdown_categories
So you can replace
get_field_id( 'category' ); ?>" name="get_field_name( 'category' ); ?>" type="text" value="" />
with a call to the wp_dropdown_categories function.

Passing data from DB to update form using CI CRUD

I'm trying to write a compact update controller for CRUD activity. Here is the basic code:
Controller:
function update($id)
{
$this->form_validation->set_rules('name','Name','required');
$this->form_validation->set_rules('age','Age','required|is_numeric');
$this->form_validation->set_rules('country','Country','');
$this->form_validation->set_error_delimiters('<br /><span class="error">', '</span>');
if ($this->form_validation->run() == FALSE) {
//Failed validation or first run
$data = $this->my_model->get_record($id);
$this->load->view('myform_view', $data);
} else {
//Validation success, update DB
}
}
View:
<?php
$attributes = array('class' => '', 'id' => '');
echo form_open('my_form', $attributes); ?>
<p>
<label for="name">Name</label>
<?php echo form_error('name'); ?>
<br /><input id="name" type="text" name="name" value="<?php echo set_value('name'); ?>" />
</p>
<p>
<label for="age">Age</label>
<?php echo form_error('age'); ?>
<br /><input id="age" type="text" name="age" value="<?php echo set_value('age'); ?>" />
</p>
<p>
<label for="country">Country</label>
<?php echo form_error('country'); ?>
<br /><input id="country" type="text" name="country" value="<?php echo set_value('country'); ?>" />
</p>
<p>
<?php echo form_submit( 'submit', 'Submit'); ?>
</p>
<?php echo form_close(); ?>
This is the basic structure, however the first time the form is run there is no validated data. Therefore I have to grab this from the DB. Whats the best way to pass this to the view on the first run? And then once the form has been submitted, if validation fails then I want the failed data to show not to reload from the DB again. Whats the best way to do this?
You should have another method for the viewing aspect. Then submit your form against the "update" method. In there, you define the the form_validation as you have now.
I asked a similar question. See this link
grab the data in update controller first for edit such as
$query = $this->db->where('id',$id)->get('table_name');
$data['edit'] = $query->result_array();
and then check it in view file
value="<?php if(isset($edit[0]['age'])){echo $edit[0]['age'];}else{echo set_value('age');}?>"