Showing undefined variable while updating image in laravel - laravel

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()
]
]);
}
}

Related

Group of checkbox always return empty values

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');
}
}

Can Anyone Check This Image Upload Code In Laravel?

I wrote this Code For Image Upload but I do not know if it is secure, or not. Is There any issue or vulnerability in this code??
if($request->hasFile('image')){
$AllowedImages = ['jpeg', 'jpg', 'png'];
$AllowedImageTypes = ['image/jpeg', 'image/png'];
$image = $request->image;
$ImageNameWithExtension = $image->getClientOriginalName();
$ImageName = pathinfo($ImageNameWithExtension, PATHINFO_FILENAME);
$ImageExtension = $image->getClientOriginalExtension();
$ImageType = $image->getMimeType();
$ImageLocalPath = $image->getPathName();
$ImageSize = $image->getSize();
$ImageError = $image->getError();
$ImageNewName = sha1(md5($ImageName)).''.sha1(time()).'.'.$ImageExtension;
if(in_array($ImageType, $AllowedImageTypes) && in_array($ImageExtension, $AllowedImages) && getimagesize($ImageLocalPath) && ($ImageError === 0) && ($ImageSize <= 2000000)){
if($ImageType == 'image/jpeg' && ( $ImageExtension == 'jpeg' || $ImageExtension == 'jpg')){
$img = imagecreatefromjpeg($ImageLocalPath);
imagejpeg( $img, $ImageNewName, 100);
}
elseif($ImageType == 'image/png' && $ImageExtension == 'png'){
$img = imagecreatefrompng($ImageLocalPath);
imagepng( $img, $ImageNewName, 9);
}
imagedestroy($img);
try
{
$StoreImage = $image->storeAs('public/Upload/', $ImageNewName);
if(!$StoreImage){
throw new customException('File Upload Failed');
}
}
catch(customException $e){
session()->flash('File_Error', $e->errorMessage());
return back();
}
}
else{
session()->flash('File_Error', 'Image Validation Error Found');
return back();
}
}
else{
return back();
}
Consider this refactor for your code, it will help make your code cleaner.
public function store(Request $request)
{
$record = Model::create( $this->validateRequest() ); // this can insert other data into your database. In the db table, initially set the image related fields to nullable
$this->storeFile($record); // this will check if the request has a file and update the image related fields accordingly, else it will remain blank as it is nullable by default
return 'all data is saved';
}
private function validateRequest(){
return request()->validate([
'type' => 'nullable',
'image'=> request()->hasFile('image') ? 'mimes:jpeg,jpg,png|max:2000' : 'nullable', // 2000 means a maximum of 2MB
'other_field_1' => 'required',
'other_field_2' => 'required',
'other_field_3' => 'required'
]);
}
private function storeFile($record){
if( request()->hasFile('image') ){
$record->update([
'type' => request()->file->extension(),
'image' => request()->file->store('uploads/files', 'public') // The file will be hashed by default. public is used as second argument so you can access the uploaded file via your public folder
]);
}
}
This is check for file in the request, validate the file and other data, upload the file into storage folder.
You can use this code, for upload image :
In Request file :
public function rules()
{
return [
'image' => 'required|mimes:jpeg,jpg,png|max:50000'
],
}
And in your controller :
public function uploadImage(YourRequestClass $request){
$image = $request->file('image');
try{
$order=new Order();
if (!file_exists('upload/' . $image)) {
$currentDate = Carbon::now()->toDateString();
$imageName = $currentDate . '-' . uniqid() . '.' . $image->getClientOriginalExtension();
if (!file_exists('upload/')) {
mkdir('upload/', 0777, true);
}
$image->move('upload/', $imageName);
$order->image = $imageName;
}
$order->save();
return back();
} catche(\Exception $e){
Log::error($e);
return back();
}
}

getting an error Undefined property: stdClass::$id

I've issue with my CMS whenever I tried to Add new page with the following line of code
<?php echo form_open_multipart('admin/page/edit/'. $page->id); ?>
it gives me error
A PHP Error was encountered
Severity: Notice
Message: Undefined property: stdClass::$id
Filename: page/edit.php
Line Number: 5
my edit function is this which perform add & update functionality
public function edit($id = NULL) {
//Fetch a page or set new one
if ($id) {
$this->data['page'] = $this->page_m->get($id);
count($this->data['page']) || $this->data['errors'][] = 'Page Could not be found';
} else {
$this->data['page'] = $this->page_m->get_new();
}
$id == NULL || $this->data['page'] = $this->page_m->get($id);
//Pages for dropdown
$this->data['pages_no_parents'] = $this->page_m->get_no_parents();
//dump($this->data['pages_no_parents']);
//Setup form
$rules = $this->page_m->rules;
$this->form_validation->set_rules($rules);
//Process the form
if ($this->form_validation->run() == TRUE) {
$data = $this->page_m->array_from_post(array(
'title',
'slug',
'order',
'body',
'template',
'parent_id',
'filename'
));
/* * ***********WORKING FOR IMAGE UPLOAD AND SAVE PATH TO DATABASE*************** */
if (!empty($_FILES['filename'])) {
$fdata = $this->do_upload('filename'); /// you are passing the parameter here
$data['filename'] = base_url() . 'uploads/' . $fdata;
}
$this->page_m->save($data, $id);
// echo '<pre>' . $this->db->last_query() . '</pre>';
redirect('admin/page');
}
//Load the view
$this->data['subview'] = 'admin/page/edit';
$this->load->view('admin/_layout_main', $this->data);
}
public function do_upload($field_name) { // but not retriveing here do this
$field_name = 'filename';
$config = array(
'allowed_types' => '*',
'max_size' => '1024',
'max_width' => '1024',
'max_height' => '768',
'upload_path' => './uploads/'
);
$this->load->library('upload');
$this->upload->initialize($config);
if (!$this->upload->do_upload($field_name)) {
echo $this->upload->display_errors();
die();
$this->data['error'] = array('error' => $this->upload->display_errors());
//$this->data['subview'] = 'admin/page/edit';
//$this->load->view('admin/_layout_main', $this->data);
} else {
$fInfo = $this->upload->data();
//return $fInfo['file_path'].$fInfo['file_name'];
// $this->filename = $fInfo;
return $fInfo['file_name'];
}
}
<?php echo form_open_multipart('admin/page/edit/'. ((isset($page->id)) ? $page->id : '')); ?>
As I mentioned in my comment, if you are creating a new record (I assume:) your page object will not have an id yet, so you just have to do a quick check to make sure it exists and if not output an empty string.

Varien_File_Uploader is not uploading files in custom module in magento

I am trying to save the images in my module but the images are not saving from the form.
$uploader = new Varien_File_Uploader('image'); this code is not working I dont know why. The loop breaks on this line and the control get out of the loop from here. How can I save the images.
Here is my save function in the controller
public function saveAction()
{
if ($this->getRequest()->getPost())
{
try
{
$postData = $this->getRequest()->getPost();
//echo "<pre>";print_r($postData); exit;
$articleModel = Mage::getModel('blog/article');
$imgFilename = NULL;
if($_FILES['image']['name'] != '')
{//echo "<pre>"; echo count($_FILES['image']['name']);
foreach($_FILES['image']['name'] as $_FILES['image']['name'])
{
//print_r($_FILES['image']['name']);
try
{ echo "1";
$uploader = new Varien_File_Uploader('image'); echo "hi";
//print_r($uploader);exit;
$uploader->setAllowedExtensions(array('jpg','jpeg','gif','png','flv'));
$uploader->setAllowRenameFiles(false);
$uploader->setFilesDispersion(false);
$uploader->setAllowCreateFolders(true);
// Set media as the upload dir
$media_path = Mage::getBaseDir('media') . DS . 'blog' . DS;
$imgFilename = time() . $postData['image'];
// Upload the image
//$uploader->save($media_path, $_FILES['image']['name']);echo "4";
$uploader->save($media_path, $imgFilename);
}
catch (Exception $e)
{
Mage::log($e);
$this->_redirectError(502);
}
$data['image'] = $imgFilename;
}
}
else
{
if(isset($data['image']['delete']) && $data['image']['delete'] == 1)
$data['image'] = '';
else
unset($data['image']);
}
//echo "out"; exit;
if( $this->getRequest()->getParam('id') <= 0 )
$articleModel->setCreatedTime(
Mage::getSingleton('core/date')
->gmtDate());
$articleModel
->addData($postData)
->setUpdatedTime(
Mage::getSingleton('core/date')
->gmtDate())
->setId($this->getRequest()->getParam('id'))
->save();
$lastid = $articleModel->getId();
if($data['image'] != '')
{
foreach($data['image'] as $img)
{
$imageModel=Mage::getModel('blog/image');
$imageModel->setArticleId($lastid)->setImage($data['image'])->save();
}
}
Mage::getSingleton('adminhtml/session')
->addSuccess('successfully saved');
Mage::getSingleton('adminhtml/session')
->setarticleData(false);
$this->_redirect('*/*/');
//return;
if ($this->getRequest()->getParam('back'))
{
$this->_redirect('*/*/edit',array('id' => $articleModel->getId()));
return;
}
}
catch (Exception $e)
{
Mage::getSingleton('adminhtml/session')
->addError($e->getMessage());
Mage::getSingleton('adminhtml/session')
->setarticleData($this->getRequest()
->getPost());
$this->_redirect('*/*/edit',
array('id' => $this->getRequest()
->getParam('id')));
return;
}
}
$this->_redirect('*/*/');
}
and here is my form for the image
<?php
class Vertax_Blog_Block_Adminhtml_Article_Edit_Tab_Image extends Mage_Adminhtml_Block_Widget_Form
{
protected function _prepareForm()
{
$form = new Varien_Data_Form();
$this->setForm($form);
$fieldset = $form->addFieldset('image_form',
array('legend'=>'image'));
//$fieldset->addType('image', Mage::getConfig()->getBlockClassName('blog/adminhtml_article_helper_image'));
$fieldset->addType('image', 'Vertax_Blog_Block_Adminhtml_Article_Helper_Image');
$fieldset->addField('image', 'image', array(
'label' => 'Image',
'required' => false,
'name' => 'image[]',
'multiple' => 'multiple',
'mulitple' => true,
));
if (Mage::getSingleton('adminhtml/session')->getBlogPostData()) {
$form->setValues(Mage::getSingleton('adminhtml/session')->getBlogPostData());
Mage::getSingleton('adminhtml/session')->setBlogPostData(null);
} elseif (Mage::registry('article_data')) {
$form->setValues(Mage::registry('article_data')->getData());
}
return parent::_prepareForm();
}
}
?>
$uploader = new Mage_Core_Model_File_Uploader(
array(
'name' => $_FILES['galleryImage']['name'][$i],
'type' => $_FILES['galleryImage']['type'][$i],
'tmp_name' => $_FILES['galleryImage']['tmp_name'][$i],
'error' => $_FILES['galleryImage']['error'][$i],
'size' => $_FILES['galleryImage']['size'][$i]
));
Waseem,please try code for upload image..
$uploader = new Mage_Core_Model_File_Uploader('image');
$uploader->setAllowedExtensions(array('jpg', 'jpeg', 'gif', 'png'));
$uploader->setFilesDispersion(true);
$media_path = Mage::getBaseDir('media') . DS . 'blog' . DS;
$imgFilename = time() . $postData['image'];
// Upload the image
//$uploader->save($media_path, $_FILES['image']['name']);echo "4";
$uploader->save($media_path, $imgFilename);
there was a problem in your code while adding fieldset
$fieldset->addField('image', 'image', array(
'label' => 'Image',
'required' => false,
'name' => 'image[]',
'multiple' => 'multiple',
'mulitple' => true,
));
here you had set the name to image[] which in turn will return the array as $_FILES['image][name][], $_FILES['image][tmp_name][].
If you want to upload single file then set 'name' = 'image' or see this question
Try to use
$uploader = new Varien_File_Uploader($_FILES['image']);
instead of what you use currently.

CodeIgniter: Passing fields to user_profiles database with Tank_auth

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);
}

Resources