i have a strange problem with laravel and checkbox.
I have a group of checkbox and I'm not able to have value to save on database.
My migration:
$table->json('send_reminder')->nullable();
My model:
protected $fillable = [
.....
'send_reminder',
....
];
my index.php
class Index extends Component{
public
....
$send_reminder,
....
My form index.blade.php
<div class="input-group input-group-static my-3">
<div class="form-control #error('reminder') is-invalid #enderror">
Notification interval: <br>
#foreach(\App\Enums\ReminderInterval::options() as $option => $reminder)
<label>
<input name="send_reminder[]" value="{{(str_replace('_','',$option))}}"
type="checkbox">
{{(str_replace('_',' ',$option))}}
</label><br>
#endforeach
</div>
When I try to save data to variable and DD the data, the field is always null.
$data = [
....other data...
'send_reminder' => $this->send_reminder
];
dd($data);
Can you help me?
thanks!
---- complete code of function path: app/Http/Livewire/User/Dashboard/Deadlines/Add/Index.php
public function Add(){
$msg = [
'check_reminder' => 'Select Reminder',
'check_reminder.in' => 'Select Reminder',
'note.required' => 'Please add a public note.',
];
$validated = $this->validate([
'customer_id' => 'required|numeric',
'name' => 'required|string',
'date' => 'required|date',
'amount' => array('required','regex:/^[0-9]{1,3}(,[0-9]{3})*(\.[0-9]+)*$/'),
], $msg);
// max customers with current subscription
$customer_of_user = count(DB::table("customers")->where("user_id", Auth::user()->id)->get());
$allowed_customers = Admin::ProductAllowedCustomers($this->active_subscription->name);
if (!$allowed_customers) {
$this->allowed_deadlines = "unlimited";
}
try {
//MAX Deadlines created about this user
$deadline_of_customer = DB::table('deadlines')
->where('customer_id', $validated['customer_id'])
->where('user_id',Auth::user()->id)
->get();
$deadline_of_customer = count($deadline_of_customer);
//Allowed Deadlines
$allowed_deadlines = Admin::ProductAllowedDeadlines($this->active_subscription->name);
//If allowed customers are unlimited
if ($this->allowed_deadlines == "unlimited" OR $deadline_of_customer < $allowed_deadlines) {
$data = [
'subscription_id' => $this->active_subscription->id,
'user_id' => Auth::user()->id,
'slug' => strtoupper(Str::random(20)),
'renew_state' => $this->renew_state,
'type_of_renew' => $this->type_of_renew,
'send_reminder' => $this->send_reminder
];
dd($data);
//Create Deadline
Deadline::create(array_merge($data, $validated));
//Get Reminder Values
// switch($this->reminder) {
// case('1_day_before'):$this->reminder = 1; break;
// case('7_days_before'):$this->reminder = 7; break;
// case('30_days_before'):$this->reminder = 30; break;
// case('60_days_before'):$this->reminder = 60; break;
// default: $this->reminder = 0;
// }
//Send Email
/*if($this->reminder):
dispatch(function () {
//Get Renew State Values
switch ($this->renew_state){
case($this->renew_state == "to_renew"): $this->renew_state = "To Renew"; break;
case($this->renew_state == "waiting_cash"): $this->renew_state = "Waiting for Cash"; break;
case($this->renew_state == "renewed"): $this->renew_state = "Renewed"; break;
default:$this->renew_state = "Deleted";
}
//Get Type of Renew Values
switch ($this->type_of_renew){
case($this->type_of_renew == "domain"): $this->type_of_renew = "Domain"; break;
case($this->type_of_renew == "hosting"): $this->type_of_renew = "Hosting"; break;
case($this->type_of_renew == "privacy_cookie"): $this->type_of_renew = "Privacy Cookie"; break;
default:$this->type_of_renew = "Other";
}
//Find Customer
$customer = Customer::find($this->customer_id);
//Data to send
$data = [
'name' => $customer->name,
'type_of_renew' => $this->type_of_renew,
'renew_state' => $this->renew_state,
'date' => date('d-M-Y'),
'note' => $this->note,
'amount' => $this->amount . ' ' . strtoupper(Admin::Currency()),
];
//Mail To
Mail::to($customer->email)->send(new Reminder($data,Auth::user()->id));
//Delay
})->delay(now()->addDays($this->reminder));
endif;*/
session()->flash('success', 'Added Successfully');
return redirect(route('UserDeadlines'));
}
else {
session()->flash('error', 'Your subscription allows you to create only ' . $allowed_deadlines .
' Deadlines for each Customer.Please upgrade your Subscription');
// return redirect(route('UserDeadlines'));
}
} catch (Exception $e) {
return session()->flash('error', $e->getMessage());
}
}
Not sure about the rest of your code, if you posted it all you would be able to get more help. That being said, livewire will not just look for inputs on your page, you need to let it know by using wire:model="send_reminder":
Working example: Example
test-field.blade.php
<div>
<input wire:model="send_reminder" name="send_reminder[]" value="1" type="checkbox">
<input wire:model="send_reminder" name="send_reminder[]" value="2" type="checkbox">
<input wire:model="send_reminder" name="send_reminder[]" value="3" type="checkbox">
<input wire:model="send_reminder" name="send_reminder[]" value="4" type="checkbox">
<div>{{ print_r($send_reminder) }}</div>
</div>
TestField.php
class TestField extends Component
{
public $send_reminder = array();
public function render()
{
return view('livewire.test-field');
}
}
Related
I am totally new in laravel and i have a small error in my code. Whenever I am updating the image it is showing the error
Undefined variable: company_image
Here is my code in Controller :
if(isset($request->company_image) && $request->company_image->getClientOriginalName()) {
$ext = $request->company_image->getClientOriginalExtension();
$file = date('YmdHis').rand(1,99999).'.'.$ext;
$request->company_image->storeAs('public/company-logo',$file);
}
else
{
if(!$company_image){
$file='';
}
else
{
$file = $company_image;
}
}
Here is my code in resource :
<div class="form-group">
<div class="row">
<div class="col-md-3">
<label>Company Image</label>
</div>
<div class="col-md-9">
<input type="file" name="company_image" id="imageUpload" class="hide">
<label for="imageUpload" class="upload-poster mr-5">Select file</label> Max Size 2 MB<br>
#if($company_image)
<img src="{{ asset('storage/company-logo/'.$company_image)}}" class="organisation-logo">
#else
<img src="{{ asset('assets/admin/images/dummy-logo.jpg')}}" id="imagePreview" class="organisation-logo" alt="Your image will appear here.">
#endif
</div>
</div>
</div>
Please help me out, Thanks in advance.
Here is my code from where I am updating the data and the image. Please check this
public function update(Request $request, $jobId)
{
try
{
if(isset($request->company_image) && $request->company_image->getClientOriginalName()){
$ext = $request->company_image->getClientOriginalExtension();
$file = date('YmdHis').rand(1,99999).'.'.$ext;
$request->company_image->storeAs('public/company-logo',$file);
}
else
{
if(!$company_image){
$file='';
}
else{
$file = $company_image;
}
}
$data = [
'job_title' => $request->input('job_title'),
'job_description' => $request->input('job_description'),
'publish_date' => Carbon::parse($request->input('publish_date'))->format('Y-m-d'),
'closing_date' => Carbon::parse($request->input('closing_date'))->format('Y-m-d'),
'company_image' => $file,
'organisation_type' => $request->input('organisation_type'),
'organisation' => $request->input('organisation'),
'country' => $request->input('country'),
'state' => $request->input('state'),
'city' => $request->input('city'),
'posted_by' => $userId
];
$rs = null;
if($request->input('temp_job') == 1){
$rs = Job::updateOrCreate(['temp_job_id'=> $jobId], $data);
}
else{
$rs = Job::where(['id'=> $jobId])->update($data);
}
if($rs){
$message = array('flag'=>'alert-success', 'message'=>'Job Updated Successfully');
return redirect()->route('auth.job.index')->with(['message'=>$message]);
}
$message = array('flag'=>'alert-danger', 'message'=>'Unable to update new job, Please try again');
return redirect()->route('auth.job.index')->with(['message'=>$message]);
}
catch (Exception $e)
{
$message = array('flag'=>'alert-danger', 'message'=>$e->getMessage());
return back()->with(['message'=>$message]);
}
}
Make sure , you are passing company_image variable in view.
if(!$company_image){
$file='';
}else{
$file = $company_image;
}
problem is here, you need to make sure $company_image is declared, before you can use it in if statement inside controller.
Example:
//declare company_image
$company_image = ''; //or $company_image = null;
//here logic to change $company_image if needed
//check if not empty/false
if(!$company_image){
$file='';
}else{
$file = $company_image;
}
Also you can check if variable exist with isset():
if(isset($company_image) && !$company_image){
$file='';
}else{
$file = $company_image;
}
Also make sure you pass this varaible in view. view('myView', compact('company_image'))
Updated Answer:
//Declare file as empty
$filePath = '';
//check if file uploaded and is valid
if($request->hasFile('company_image') && $request->file('company_image')->isValid()){
//get file extension
$ext = $request->company_image->extension();
//Generate File name
$file = date('YmdHis').rand(1,99999).'.'.$ext;
//Save file, storeAs() will return stored file path
$filePath = $request->company_image->storeAs('public/company-logo',$file);
}
Use $filePath to update the path in DB
$data = [
...
'company_image' => $filePath,
...
];
In view you can simply use {{ asset($company_image) }} check Laravel docs
Complete update function
public function update(Request $request, $jobId) {
try{
//Declare file as empty
$filePath = '';
//check if file uploaded and is valid
if($request->hasFile('company_image') && $request->file('company_image')->isValid()){
//get file extension
$ext = $request->company_image->extension();
//Generate File name
$file = date('YmdHis').rand(1,99999).'.'.$ext;
//Save file, storeAs() will return stored file path
$filePath = $request->company_image->storeAs('public/company-logo', $file);
}
$data = [
'job_title' => $request->input('job_title'),
'job_description' => $request->input('job_description'),
'publish_date' => Carbon::parse($request->input('publish_date'))->format('Y-m-d'),
'closing_date' => Carbon::parse($request->input('closing_date'))->format('Y-m-d'),
'company_image' => $filePath,
'organisation_type' => $request->input('organisation_type'),
'organisation' => $request->input('organisation'),
'country' => $request->input('country'),
'state' => $request->input('state'),
'city' => $request->input('city'),
'posted_by' => $userId
];
$rs = null;
if($request->input('temp_job') == 1){
$rs = Job::updateOrCreate([
'temp_job_id'=> $jobId
], $data);
} else{
$rs = Job::where([
'id' => $jobId
])->update($data);
}
if($rs){
return redirect()->route('auth.job.index')->with([
'message' => [
'flag' => 'alert-success',
'message' => 'Job Updated Successfully'
]
]);
}
return redirect()->route('auth.job.index')->with([
'message'=> [
'flag' => 'alert-danger',
'message' => 'Unable to update new job, Please try again'
]
]);
}catch (Exception $e){
return back()->with([
'message'=> [
'flag' => 'alert-danger',
'message' => $e->getMessage()
]
]);
}
}
I'm having difficulty getting this to create a category on the front-end with Ajax. It's 99% working.
Here is my form:
<form id="new_idea" name="new_idea" method="POST">
<ul>
<li>
<label>Idea name</label>
<input type="text" name="idea_name" required />
</li>
<li class="full">
<label>Description</label>
<input type="text" name="idea_description" />
</li>
</ul>
</form>
Here is my function (in functions.php):
add_action( 'wp_ajax_add_new_idea', 'add_new_idea' );
add_action( 'wp_ajax_nopriv_add_new_idea', 'add_new_idea' );
function ajax_scripts() {
$parameters = array(
'ajaxurl' => admin_url('admin-ajax.php'),
'nonce' => wp_create_nonce('inputs')
);
wp_enqueue_script('my-ajax', get_template_directory_uri().'/js/ajax.js', array('jquery'), null, true);
wp_localize_script('my-ajax', 'inputs', $parameters );
}
add_action('wp_enqueue_scripts', 'ajax_scripts');
function ajaxStatus($status, $message, $data = NULL) {
$response = array (
'status' => $status,
'message' => $message,
'data' => $data
);
$output = json_encode($response);
exit($output);
}
// New Idea
function add_new_idea() {
if(isset($_POST["new_idea_form"])) {
ajaxStatus('error', 'No need to update anything.');
} else {
$nonce = $_POST['nonce'];
if(wp_verify_nonce($nonce, 'inputs') !== false) {
require_once(ABSPATH . 'wp-admin/includes/taxonomy.php');
$idea_name = $_POST['idea_name'];
$idea_description = $_POST['idea_description'];
$idea_slug = sanitize_title_with_dashes($idea_name);
$idea = array(
'cat_name' => $idea_name,
'category_parent' => '',
'category_nicename' => $idea_slug,
'category_description' => $idea_description,
'taxonomy' => 'ideas'
);
wp_insert_category( $idea );
//print_r($idea);
//die;
// Success message
ajaxStatus('success', 'Added new idea');
} else {
// No nonce!
ajaxStatus('error', 'Nonce failed!');
}
}
}
...and this is my ajax.js:
$('#new_idea').on('submit', function(e) {
e.preventDefault();
$.post( inputs.ajaxurl, {
action : 'add_new_idea',
nonce : inputs.nonce,
post : $(this).serialize()
},
function(response) {
console.log(response);
ResponseSuccess(response);
});
return false;
});
As for troubleshooting, if I hardcode values into the $idea array like this and submit the form...
$idea = array(
'cat_name' => 'cool idea',
'category_parent' => '',
'category_nicename' => 'cool-dea',
'category_description' => 'a description of my cool idea',
'taxonomy' => 'ideas'
);
...it actually works and my category gets created.
So from what I can tell, the real problem is that it is not getting the $_POST[] values that were submitted, although I can't see why.
Any help would be awesome.
Try this code.
function add_new_idea() {
$params = array();
parse_str($_POST["post"], $params);
if(isset($_POST["post"])) {
ajaxStatus('error', 'No need to update anything.');
} else {
$nonce = $_POST['nonce'];
if(wp_verify_nonce($nonce, 'inputs') !== false) {
require_once(ABSPATH . 'wp-admin/includes/taxonomy.php');
$idea_name = $params['idea_name'];
$idea_description = $params['idea_description'];
$idea_slug = sanitize_title_with_dashes($idea_name);
$idea = array(
'cat_name' => $idea_name,
'category_parent' => '',
'category_nicename' => $idea_slug,
'category_description' => $idea_description,
'taxonomy' => 'ideas'
);
wp_insert_category( $idea );
//print_r($idea);
//die;
// Success message
ajaxStatus('success', 'Added new idea');
} else {
// No nonce!
ajaxStatus('error', 'Nonce failed!');
}
}
}
Read This
you need to use parse_str for serlize object.
Retrieving serialize data in a PHP file called using AJAX
I have a form with these fields:
shipping_method (hidden field with value="2" in my testing case)
courier_id
tracking_no
delivery_date
The courier_id field is required only if the shipping_method is 2
<div class="form-group{{ $errors->has('courier_id') ? ' has-error' : ''}}">
<label>Courier</label>
<select name="courier_id" class="form-control">
<option value="">Select...</option>
#foreach($couriers as $courier)
<option value="{{ $courier->id }}">{{ $courier->name }}</option>
#endforeach
</select>
#if ($errors->has('courier_id'))
<span class="help-block">
<strong>{{ $errors->first('courier_id') }}</strong>
</span>
#endif
</div>
In my controller:
public function update(Request $request, $id)
{
$delivery_date = Null;
$courier_id = Null;
$order = Order::findOrFail($id);
$status = 0;
if($order->status == 2) {
$status = 3;
$courier_id = $request->courier_id;
$messages = [ 'courier_id.required' => 'Please select a courier'];
$v = Validator::make(Input::all(), [
'tracking_no' => 'required',
'delivery_date' => 'required|date_format:d/m/Y'
], $messages)->validate();
$v->sometimes('courier_id', 'required', function (Request $request) {
return true;
//return $request->shipping_method == 2;
});
Even though the courier_id is empty, I don't get the error for it.
I have three questions:
Why even when I just return true on the sometimes check, I don't get the error
Not sure what is the parameter I should send to the sometimes check, is it Request $request?
I tried to send the order to the sometimes check instead of the request so I won't have to have a hidden field for it on the form, e.g.
$v->sometimes('courier_id', 'required', function ($order) {
return $order->shipping_method == 2;
});
Again, no error is displayed.
The order status is 2 for sure.
I also tried:
$v->sometimes('courier_id', 'required', function ($order) {
return $order->shipping_method == '2';
});
If I remove the sometimes check, and just add the courier_id validation as required, I do get the error on the form.
You are adding the conditional rule after you validate the data thus making the validator uninformed about that rule. That should answer your first question
For your question 2, 3 the document states that
The $input parameter passed to your Closure will be an instance of Illuminate\Support\Fluent and may be used to access your input and files.
First add the custom rule to the validator. Then validate the data.
$v = Validator::make(Input::all(), [
'tracking_no' => 'required',
'delivery_date' => 'required|date_format:d/m/Y'
], $messages);
$v->sometimes('courier_id', 'required', function (Request $request) {
return $request->shipping_method == 2;
});
$v->validate();
You should be able to do this without a conditional rule.
You can add the following to your existing rule set which should validate
'courier_id' => 'required_if:shipping_method,2'
So your validation should be
$v = Validator::make(Input::all(), [
'tracking_no' => 'required',
'delivery_date' => 'required|date_format:d/m/Y',
'courier_id' => 'required_if:shipping_method,2'
], $messages)->validate();
i have a login method but it doesn't seems to work correctly. For example if i try to login with a username that exists in the database and the password of another user, i can successfully login. Can someone spot the error in my code?
Controller:
public function login(){
$this->load->library('form_validation');
$this->form_validation->set_error_delimiters('', '');
$this->form_validation->set_rules('name_login', 'Utilizator', 'required|callback_validate_login|xss_clean|trim');
$this->form_validation->set_rules('password_login', 'Password', 'required|xss_clean|trim');
$this->form_validation->set_message('validate_login','login esuat');
$this->form_validation->set_message('required', '*');
if ($this->form_validation->run() === FALSE){
$this->render('login');
}
else {
// user successful login
$data = array(
'username' => $this->input->post('name_login'),
'is_logged_in' => 1
);
$this->session->set_userdata($data);
$this->load->view('homeview',$data);
}
}
public function validate_login(){
$username = $this->input->post('user_login');
$pass = $this->input->post('password_login');
if ($this->homemodel->login($username,$pass)){
return true;// form validation passed, u are now logged in
}
else {
return false;
}
}
Model:
public function login($user, $pass)
{
$query = $this->db->get_where('login', array('username' => $user, 'password' => $pass));
echo '<pre>';
print_r($query->result());
echo '</pre>';
if ($query->num_rows() === 1) {
return true;
} else {
return false;
}
View
<?php echo form_open('home/login') ?>
<label for="user">Username</label>
<input type="text" class="createform" name="user_login" value="<?php echo set_value('name_login'); ?> " />
<?php echo form_error('name_login') . '<br>'; ?>
<label for="pass">Password</label>
<input type="text" class="createform" name="password_login" value="<?php echo set_value('password_login'); ?> " />
<?php echo form_error('password_login') . '<br>'; ?>
<input type="submit" name="submit" value="Login" />
</form>
Oh,my bad, found the error : the username input name in the view file is "user_login" and in the controller i wrote 'name_login':
$this->form_validation->set_rules('name_login',...)
It looks like you are setting the session data to is_logged_in just on successful form submission:
if ($this->form_validation->run() === FALSE){
$this->render('login');
}
else {
// user successful login
$data = array(
'username' => $this->input->post('name_login'),
'is_logged_in' => 1
);
You need to validate the user first.
I would try something like:
if ($this->form_validation->run() === FALSE){
$this->render('login');
}
else {
$results = $this->validate_login();
// user successful login
if ($results){
$data = array(
'username' => $this->input->post('name_login'),
'is_logged_in' => 1
);
$this->session->set_userdata($data);
$this->load->view('homeview',$data);
}
else {
redirect('login');
}
}
Does that make sense? It doesn't look like you were actually checking or calling the validate_login() method.
I'm wracking my brain on what is probably a simple issue. Relatively new to MVC and codeigniter. I'm using tank_auth for user registration, and it comes with a db table user_profiles which I've altered slightly to add things like 'firstname', 'lastname', 'homephone', etc.
I've added the appropriate fields to my register_form.php view and following advice from this question: Tank Auth Adding Fields and others, tried to update all necessary stuff. Unfortunately, while the users table gets populated properly, the user_profiles table does not. I've double checked with firebug that the view is posting properly, but the model is not picking up the data, and I keep getting the error:
A PHP Error was encountered
Severity: Notice
Message: Undefined variable: firstname
Filename: tank_auth/users.php
Line Number: 382
Using var_dump, I can see that the controller function is not receiving 'firstname' or anything else and they are NULL, but the data going into users is being sent properly.
Here's the relevant code:
Model:
private function create_profile($user_id)
{
$this->db->set('user_id', $user_id);
$this->db->set('firstname', $firstname);
return $this->db->insert($this->profile_table_name);
}
Controller:
function register()
{
if ($this->tank_auth->is_logged_in()) { // logged in
redirect('');
} elseif ($this->tank_auth->is_logged_in(FALSE)) { // logged in, not activated
redirect('/auth/send_again/');
} elseif (!$this->config->item('allow_registration', 'tank_auth')) { // registration is off
$this->_show_message($this->lang->line('auth_message_registration_disabled'));
} else {
$use_username = $this->config->item('use_username', 'tank_auth');
if ($use_username) {
$this->form_validation->set_rules('username', 'Username', 'trim|required|xss_clean|min_length['.$this->config->item('username_min_length', 'tank_auth').']|max_length['.$this->config->item('username_max_length', 'tank_auth').']|alpha_dash');
}
$this->form_validation->set_rules('email', 'Email', 'trim|required|xss_clean|valid_email');
$this->form_validation->set_rules('firstname', 'Firstname', 'trim|xss_clean');
$this->form_validation->set_rules('lastname', 'Lastname', 'trim|xss_clean');
$this->form_validation->set_rules('password', 'Password', 'trim|required|xss_clean|min_length['.$this->config->item('password_min_length', 'tank_auth').']|max_length['.$this->config->item('password_max_length', 'tank_auth').']|alpha_dash');
$this->form_validation->set_rules('confirm_password', 'Confirm Password', 'trim|required|xss_clean|matches[password]');
$captcha_registration = $this->config->item('captcha_registration', 'tank_auth');
$use_recaptcha = $this->config->item('use_recaptcha', 'tank_auth');
if ($captcha_registration) {
if ($use_recaptcha) {
$this->form_validation->set_rules('recaptcha_response_field', 'Confirmation Code', 'trim|xss_clean|required|callback__check_recaptcha');
} else {
$this->form_validation->set_rules('captcha', 'Confirmation Code', 'trim|xss_clean|required|callback__check_captcha');
}
}
$data['errors'] = array();
$email_activation = $this->config->item('email_activation', 'tank_auth');
if ($this->form_validation->run()) { // validation ok
if (!is_null($data = $this->tank_auth->create_user(
$use_username ? $this->form_validation->set_value('username') : '',
$this->form_validation->set_value('email'),
$this->form_validation->set_value('password'),
$this->form_validation->set_value('firstname'),
$this->form_validation->set_value('lastname'),
$this->form_validation->set_value('homephone'),
$this->form_validation->set_value('cellphone'),
$email_activation))) { // success
$data['site_name'] = $this->config->item('website_name', 'tank_auth');
if ($email_activation) { // send "activate" email
$data['activation_period'] = $this->config->item('email_activation_expire', 'tank_auth') / 3600;
$this->_send_email('activate', $data['email'], $data);
unset($data['password']); // Clear password (just for any case)
$this->_show_message($this->lang->line('auth_message_registration_completed_1'));
} else {
if ($this->config->item('email_account_details', 'tank_auth')) { // send "welcome" email
$this->_send_email('welcome', $data['email'], $data);
}
unset($data['password']); // Clear password (just for any case)
$this->_show_message($this->lang->line('auth_message_registration_completed_2').' '.anchor('/auth/login/', 'Login'));
}
} else {
$errors = $this->tank_auth->get_error_message();
foreach ($errors as $k => $v) $data['errors'][$k] = $this->lang->line($v);
}
}
if ($captcha_registration) {
if ($use_recaptcha) {
$data['recaptcha_html'] = $this->_create_recaptcha();
} else {
$data['captcha_html'] = $this->_create_captcha();
}
}
$data['use_username'] = $use_username;
$data['captcha_registration'] = $captcha_registration;
$data['use_recaptcha'] = $use_recaptcha;
$this->load->view('auth/register_form', $data);
}
}
View:
$firstname = array(
'name' => 'firstname',
'id' => 'firstname',
'value' => set_value('firstname'),
'maxlength' => 40,
'size' => 30,
);
...
<tr>
<td><?php echo form_label('First Name', $firstname['id']); ?></td>
<td><?php echo form_input($firstname); ?></td>
<td style="color: red;"><?php echo form_error($firstname['name']); ?><?php echo isset($errors[$firstname['name']])?$errors[$firstname['name']]:''; ?></td>
</tr>
I have been working on this far too long, am hoping that a fresh (and knowledgeable) pair of eyes can see what I cannot.
The data to be recorded in user_profile is passed along the folllowing chain:
view -> controller -> library/tank_auth/create_user() -> model/users/users/create_user() -> model/create_profile
Therefore you need to make sure that the variable is passed along every time.
Here is my working solution, building up on the modifications that you mentioned in the question:
VIEW + CONTROLER:
Your solution is good
LIBRARY
function create_user($username, $email, $password, $firstname, $lastname, $company='', $email_activation)
{
if ((strlen($username) > 0) AND !$this->ci->users->is_username_available($username)) {
$this->error = array('username' => 'auth_username_in_use');
} elseif (!$this->ci->users->is_email_available($email)) {
$this->error = array('email' => 'auth_email_in_use');
} else {
// Hash password using phpass
$hasher = new PasswordHash(
$this->ci->config->item('phpass_hash_strength', 'tank_auth'),
$this->ci->config->item('phpass_hash_portable', 'tank_auth'));
$hashed_password = $hasher->HashPassword($password);
$data = array(
'username' => $username,
'password' => $hashed_password,
'email' => $email,
'last_ip' => $this->ci->input->ip_address(),
);
$data_profile = array(
'firstname' => $firstname,
'lastname' => $lastname,
'company' => $company,
);
if ($email_activation) {
$data['new_email_key'] = md5(rand().microtime());
}
if (!is_null($res = $this->ci->users->create_user($data, $data_profile, !$email_activation))) {
$data['user_id'] = $res['user_id'];
$data['password'] = $password;
unset($data['last_ip']);
return $data;
}
}
return NULL;
}
MODEL:
function create_user($data, $data_profile, $activated = TRUE)
{
$data['created'] = date('Y-m-d H:i:s');
$data['activated'] = $activated ? 1 : 0;
var_dump($data);
if ($this->AuthDb->insert($this->table_name, $data)) {
$user_id = $this->AuthDb->insert_id();
$this->create_profile($user_id, $data_profile);
return array('user_id' => $user_id);
}
return NULL;
}
[...]
private function create_profile($user_id, $data_profile)
{
$this->AuthDb->set('user_id', $user_id);
$this->AuthDb->set('firstname', $data_profile['firstname']);
$this->AuthDb->set('lastname', $data_profile['lastname']);
$this->AuthDb->set('company', $data_profile['company']);
return $this->AuthDb->insert($this->profile_table_name);
}
You need to pass $firstname as a parameter to the function...
private function create_profile($user_id, $firstname)
{
$this->db->set('user_id', $user_id);
$this->db->set('firstname', $firstname);
return $this->db->insert($this->profile_table_name);
}
Ok so I figured it out, in case anyone googles this answer down the line. I'm not sure if this is the 'proper' or most elegant solution, but does fine for my purposes. I edited the create_profile function like so:
private function create_profile($user_id)
{
$this->db->set('user_id', $user_id);
$data = array(
'firstname' => $this->input->post('firstname'),
);
$this->db->insert($this->profile_table_name, $data);
}