PHP- Problem passing information between PHP, Angular & HTTP? - javascript

I'm working on a Laravel PHP site, and am getting an error when trying to add a user to a cell in a table
The error says:
An error has occurred adding your contact. If the problem persists, please contact us.
and is displayed in a red 'ribbon' that pops up just below the browser address bar for a few seconds when trying to select a new user from the drop down.
I have seen a couple of similar questions on SO, but can't see how any of the answers apply to what's going on here...
In the HTML, the table column whose cell value I am trying to update is done via a form that pops up in a dialog box when pressing the 'Edit' icon in the cell:
<div class="provTaxContacts__row">
<form [formGroup]="newContactForm" class="provTaxContacts__col provTaxContacts__new-contact">
<label>Add new contact</label>
<div class="provTaxContacts__new-contact-fields">
<input class="provTaxContacts__new-contact-field provTaxContacts__name" [class.error]="newContactFormErrors.contactFirstName" placeholder="First name" type="text" autocomplete="given-name" formControlName="contactFirstName" />
<input class="provTaxContacts__new-contact-field provTaxContacts__name" [class.error]="newContactFormErrors.contactLastName" placeholder="Last name" type="text" autocomplete="family-name" formControlName="contactLastName" />
<input class="provTaxContacts__new-contact-field provTaxContacts__email" [class.error]="newContactFormErrors.contactEmail" placeholder="Email address" type="email" autocomplete="email" formControlName="contactEmail" />
<button class="btn btn-primary provTaxContacts__new-contact-button" type="button" (click)="onNewContactAdd(taxpayer.accountId)">Add contact</button>
<div *ngIf="addContactLoading" class="spinner-loading"></div>
</div>
</form>
</div>
The onNewContactAdd() function that's called when pressing the 'Add Contact' button is defined in a Typescript file called tax-reminder.ts, and as well as handling what happens to the browser on the front-end, it also calls the function addUserToAccount() from user.service.ts. It is what's displaying the error in the browser, and is defined with:
onNewContactAdd(accountId: number) {
const firstName = this.newContactForm.get('contactFirstName').value;
const lastName = this.newContactForm.get('contactLastName').value;
const email = this.newContactForm.get('contactEmail').value;
// Reset error states
this.resetContactFormErrors();
// Check for form errors
if (!firstName || Validate.isEmpty(firstName) || !Validate.lettersAndSpaces(firstName)) {
this.newContactFormErrors.contactFirstName = true;
} else {
this.newContactFormErrors.contactFirstName = false;
}
if (!lastName || Validate.isEmpty(lastName) || !Validate.lettersAndSpaces(lastName)) {
this.newContactFormErrors.contactLastName = true;
} else {
this.newContactFormErrors.contactLastName = false;
}
if (Validate.isEmpty(email) || !Validate.emailRegex.test(email)) {
this.newContactFormErrors.contactEmail = true;
} else {
this.newContactFormErrors.contactEmail = false;
}
// If there are any errors at this stage, Don't add
if (this.newContactFormErrors.contactFirstName || this.newContactFormErrors.contactLastName || this.newContactFormErrors.contactEmail) {
return
}
// Reset errors, just in case there were previous erros that we now know have been resolved
this.resetContactFormErrors();
this.addContactLoading = true;
// If all is valid, send a request to create the new contact
this.userService.addUserToAccount([{firstName, lastName, email, role: 'FULL'}], 'FULL', accountId)
.subscribe(
(response: any) => {
this.addContactLoading = false;
// Reset the add contact form so that the user can add more
this.newContactForm.patchValue({
contactFirstName: '',
contactLastName: '',
contactEmail: '',
});
// If the new contact's email address is already in the on-page list do nothing
if (_.find(this.contacts[accountId], {email})) {
return;
} else {
// If the request is succcessful, add the new contact to the list of contacts
this.contacts[accountId].push({
accountId,
email,
firstName,
groupTag: 'FULL',
lastName,
provTaxManager: 0,
provTaxPaymentsContact: 0,
userId: response.userId,
//transactionContactId,
});
}
},
error => {
console.log("Error: " + error);
const message = new Message();
message.type = MessageType.ERROR;
message.message = 'An error has occurred adding your contact. If the problem persists please contact us.';
this.messagingService.emitMessage(message);
}
)
}
In the browser console, I can see the following output in the Network-> Preview tab:
array:9 [
"userId" => 9561
"title" => null
"firstName" => "Shane"
"lastName" => "Williams"
"workPhone" => null
"mobilePhone" => null
"email" => "shane#williams.com"
"userTypeId" => 3
"login" => array:3 [
"loginId" => 9449
"loginName" => "shane#williams.com"
"userId" => 9561
]
]
Which shows that the details I entered into the form have been collected, and a new user ID has been assigned.
That output is coming from a dd() I have in the addAccountUser() PHP function:
public function addAccountUser( AddAccountUsersRequest $request )
{
$users = $request->input('users');
$type = $request->input('type');
$accountId = $request->input('accountId');
$userType = $type == 'taxfirm-agent' ? UserType::where('userTypeTag', 'AGENT')->first() : UserType::where('userTypeTag', 'DIRECT')->first();
$messages = array();
$hasWarningMessages = false;
try
{
DB::beginTransaction();
foreach ($users as $userRaw)
{
$details = array(
'firstName' => $userRaw['firstName'],
'lastName' => $userRaw['lastName'],
'email' => $userRaw['email'],
'password' => uniqid(),
'userTypeId' => $userType->userTypeId,
'accountId' => (!empty($accountId)) ? $accountId : null
);
$propertyValues = array();
// Adding tax agent
if ($type == 'taxfirm-agent') {
$group = $userRaw['role'];
$rv = $this->addTaxfirmAgent($details, $group);
}
else if($type == 'taxfirm-direct') {
$rv = $this->addTaxfirmDirectContact($details);
}
else {
$group = $userRaw['role'];
$rv = $this->addTaxpayerDirectContact($details, $group);
}
DB::commit();
dd($rv['user']->toArray());
if ($rv['status'] !== 'SUCCESS') {
if (!isset($messages[$rv['status']])) {
$messages[$rv['status']] = array(
'message' => StatusMessage::getMessage($rv['status']),
'data' => [],
//dd($messages);
);
}
$messages[$rv['status']]['data'][] = [$userRaw['email'], ucfirst($userRaw['firstName']), ucfirst($userRaw['lastName'])];
//dd($messages); // success is true at this point, users are null
if (!$hasWarningMessages)
{
$hasWarningMessages = true;
}
}
}
}
catch(\Exception $e)
{
DB::rollback();
return response()->json(array(
'success' => false,
'exceptionCode' => $e->getCode(),
'exceptionMessage' => $e->getMessage().' - '.$e->getFile().' - '.$e->getLine(),
'userId' => $userId // Try returning the userId too...
), 400);
}
$outputMsg = array();
foreach ($messages as $value) {
$outputMsg[] = $value;
}
//dd($users);
return response()->json(array(
'success' => true,
'hasWarningMessages' => $hasWarningMessages,
'result' => $outputMsg,
//'users' => $rv['user']->user, /*ERF(18/09/2018 # 1630) Change to userId */
'userId' => $rv['user']->userId,
));
}
I don't fully understand how the JavaScript, PHP & HTTP are all interacting here, or why the PHP debug appears to be showing the new contact created successfully, and yet I still get the error in the browser.
Can anyone point me in the right direction here? Why is the contact seemingly created, and yet I get the error, as well as the contact not being displayed in the drop down box as I am expecting?
Edit
So, I think that the issue I'm having here is not to do with the PHP itself- as that function seems to be returning the correct information (the console output given when I added the line dd($rv['user']->toArray()) at the end of the function showed all of the details for the user I had just added correctly), but rather to do with the Angular that should be updating the front end, to display the new user in the drop down.
That function is defined as follows:
this.userService.addUserToAccount([{firstName, lastName, email, role: 'FULL'}], 'FULL', accountId)
.subscribe(
(response: any) => {
this.addContactLoading = false;
// Reset the add contact form so that the user can add more
this.newContactForm.patchValue({
contactFirstName: '',
contactLastName: '',
contactEmail: '',
});
// If the new contact's email address is already in the on-page list do nothing
if (_.find(this.contacts[accountId], {email})) {
return;
} else {
// If the request is succcessful, add the new contact to the list of contacts
this.contacts[accountId].push({
accountId,
email,
firstName,
groupTag: 'FULL',
lastName,
provTaxManager: 0,
provTaxPaymentsContact: 0,
userId: response.userId,
//transactionContactId,
});
}
},
error => {
console.log("Error: " + error);
const message = new Message();
message.type = MessageType.ERROR;
message.message = 'An error has occurred adding your contact. If the problem persists please contact us.';
this.messagingService.emitMessage(message);
}
)
I think I need to add a call to reload this page element at the end of the else statement in this function... How would I do that?
Edit
So, it seems that although the contact appears to be created, the HTTP response I'm getting is actually the error- as I can see the An error has occurred adding your contact. If the problem persists please contact us. message in the browser... Why is it that the HTTP response is failing? How can I resolve this?
I added a console.log() to display the error in the console, and it's showing the following output:
unparsable response
Error: SyntaxError: Unexpected token < in JSON at position 0
I don't understand where this error is coming from... any ideas?

Related

Prevent InvalidArgumentException on dynamic form field creation

I'm following Symfony cookbook on dynamic form fields creation.
Basically, in my case, I have a Product, a ProductVersion and a Quantity field in my form.
On new forms, ProductVersion is hidden (only with a class attribute, It's still an EntityType).
On Product change (via select menu), I make an AJAX request to see if some ProductVersion exists for this product. If so, I populate the ProductVersion with available versions and show it to the user.
It's working fine with new forms. But when editing the same form, I have an InvalidArgumentException response on my AJAX request that tells me that the Quantity field is null :
Expected argument of type "int", "null" given at property path
"quantity".
I understand that indeed, I don't provide the quantity on my form submission through the AJAX request but that's the purpose of this method isn't it ? To only submit the field that makes a dynamic field change.
How can I do to avoid this Exception ?
Here is the ItemType :
public function buildForm(FormBuilderInterface $builder, array $options)
{
$builder
->add('product', EntityType::class, [
'label' => 'item.product',
'class' => Product::class,
'placeholder' => 'item.product',
]);
$formModifier = function (FormInterface $form, Product $product = null) {
if (null !== $product) {
$productVersions = $product->getVersions();
if (count($productVersions) > 0) {
$form->add('productVersion', EntityType::class, [
'class' => 'App\Entity\ProductVersion',
'placeholder' => 'item.product_version',
'choices' => $productVersions,
'label' => 'item.product_version'
]);
} else {
$form->add('productVersion', EntityType::class, [
'class' => 'App\Entity\ProductVersion',
'placeholder' => 'item.product_version',
'choices' => [],
'label' => 'item.product_version',
'disabled' => true,
'row_attr' => [
//'class' => 'd-none'
]
]);
}
} else {
$form->add('productVersion', EntityType::class, [
'class' => 'App\Entity\ProductVersion',
'placeholder' => 'item.product_version',
'choices' => [],
'label' => 'item.product_version',
'disabled' => true,
'row_attr' => [
//'class' => 'd-none'
]
]);
}
};
$builder->addEventListener(
FormEvents::PRE_SET_DATA,
function (FormEvent $event) use ($formModifier) {
$form = $event->getForm();
$data = $event->getData();
$options = $event->getForm()->getConfig()->getOptions();
//add custom product version according product selected
$formModifier($event->getForm(), $data->getProduct());
$form
->add('quantity', IntegerType::class, [
'label' => 'item.quantity',
]);
if ($data->getId()) {
$form
->add('save', SubmitType::class, [
'label' => $options['submit_btn_label'],
]);
} else {
$form
->add('save', SubmitType::class, [
'label' => $options['submit_btn_label'],
]);
}
}
);
$builder->get('product')->addEventListener(
FormEvents::POST_SUBMIT,
function (FormEvent $event) use ($formModifier) {
// It's important here to fetch $event->getForm()->getData(), as
// $event->getData() will get you the client data (that is, the ID)
$product = $event->getForm()->getData();
// since we've added the listener to the child, we'll have to pass on
// the parent to the callback functions!
$formModifier($event->getForm()->getParent(), $product);
}
);
}
And here is the Javascript part :
$(document).ready(function () {
var $product = $('#item_product');
// When product gets selected ...
$product.on('change', function () {
console.log("product has changed")
// ... retrieve the corresponding form.
var $form = $(this).closest('form');
// Simulate form data, but only include the selected product value.
var data = {};
data[$product.attr('name')] = $product.val();
// Submit data via AJAX to the form's action path.
console.log(data);
$.ajax({
url: $form.attr('action'),
type: $form.attr('method'),
data: data,
success: function (html) {
// Replace current position field ...
$('#item_productVersion').closest('.form-group').replaceWith(
// ... with the returned one from the AJAX response.
$(html).find('#item_productVersion').closest('.form-group')
);
// Position field now displays the appropriate positions.
}
});
});
})
As #Jakumi suggested, adding an empty_data option to the quantity field solved the problem. Nevertheless, It gives an error on the quantity on the form received via the AJAX request and that's normal.
I found that this is not a "clean" method (you have to tweak form fields, you load the entire page on each AJAX request, etc..) so I decided to create a special route dedicated to form submissions that are meant to add/remove/edit fields.
This route creates a new form with preset fields (in my case the product selected by the user).
Then I can populate the other field (in my case the 'ProductVersion') with a regular PRE_SET_DATA Form Event.
This way :
- I don't have to worry about any other required field
- I can serialize the entire form in my AJAX request (no need to find the field, everything is done in the form builder)
- The AJAX request only output the form (I guess this improves performance a bit)
The form builder doesn't change (you still need to listen to PRE_SET_DATA and POST_SUBMIT. If you don't listen to the POST_SUBMIT, the form will not know about the choices you added dynamically and It will give you an error).
Here is the JS part :
$product.on('change', function() {
// ... retrieve the corresponding form.
var $form = $(this).closest('form');
// serialize the entire form
var data = $form.serializeArray();
// Submit data via AJAX to the form's action path.
console.log(data);
$.ajax({
url : '/project/item/partial-edit', //custom route
type: $form.attr('method'),
data : data,
success: function(html) {
// Replace current position field ...
$('#item_productVersion').closest('.form-group').replaceWith(
// ... with the returned one from the AJAX response.
$(html).find('#item_productVersion').closest('.form-group')
);
}
});
});
Here is the special route :
/**
* #Route("/item/partial-edit", name="edit_item_partial", requirements={"project"="\d+","item"="\d+"})
*/
public function edit_item_partial(Request $request)
{
$item = new Item();
$formOption = $request->get('option') ?? array(
'submit_btn_label' => 'update'
);
$form = $this->createForm(ItemType::class, $item, $formOption);
$form->handleRequest($request);
if ($form->isSubmitted()){
//if form was submitted, create a new form with the $item that has now a Product given
$newForm = $this->createForm(ItemType::class, $item, $formOption);
//here is the custom view only rendering the form
return $this->render('item/new_form-only.html.twig', [
'form' => $newForm->createView(),
]);
}
else {
return new Response('No form was submitted');
}
}

How to submit multiple forms in laravel?

I have a simple form which contains a button to open another form in a pop up modal, the form looks like this
Now as you can see above prebids input plus button, when the user clicks the plus button it opens the modal which contains a form like this below.
Now I want to submit the forms in the following an order
First submit: base form (norma way)
Second submit: form inside a pop up (via ajax)
Here is my store function to submit the forms in a page controller
public function store(Request $request)
{
$page = Page::create([
'title' => $request->get('title'),
'articles' => $request->get('articles'),
'status' => $request->get('status'),
]);
// dd($request);
$page->save();
$bidder = Bidder::create('page_id' -> $page->id);
// save bidders informtion to the database using ajax
if($request->ajax())
{
$rules = array(
'params_name.*' => 'required',
'params_value.*' => 'required',
'bidders_name.*' => 'required',
);
$error = Validator::make($request->all(), $rules);
if($error->fails())
{
return response()->json([
'error' => $error->errors()->all()
]);
}
$params_name = $request->params_name;
$params_value =$request->params_value;
$bidders_name =$request->bidders_name;
for($count = 0; $count < count($params_name); $count++)
{
$data = array(
'params_name' => $params_name[$count],
'params_value' => $params_value[$count],
'bidders_name' => $bidders_name[$count],
);
$insert_data[] = $data;
}
bidder_parameters::insert($insert_data);
return response()->json([
'success' => 'Data Added successfully.'
]);
}
return redirect("/pages")->with("sucess", "data saved");
}
And here is ajax for submitting form inside a pop up
$("#paramsForms").on('submit', function(e) {
e.preventDefault();
$.ajax({
url: '/pages',
type: "POST",
data: $(this).serialize(),
dataType: 'json',
beforeSend:function() {
$("#save").attr('disabled', 'disabled');
},
success:function (data) {
console.log(data);
alert('Data successfull saved');
},
error:function (error) {
console.log(error)
console.log('Data not saved');
}
})
})
Now when I click submit I get the following error
SQLSTATE[23000]: Integrity constraint violation: 1048 Column 'title' cannot be null (SQL: insert into `pages` (`title`, `articles`, `status`, `updated_at`, `created_at`) values (?, ?, ?, 2019-11-06 11:29:31, 2019-11-06 11:29:31))"
Note: checking dd($request) for both forms in a store function, I get the following
+request: ParameterBag {#44
#parameters: array:4 [
"_token" => "Wgozk9jnyUnJkL35vPhso9sUr7lbMD8cSgMVuN2s"
"bidders_name" => array:1 [
0 => "Biden"
]
"params_name" => array:1 [
0 => "democratic"
]
"params_value" => array:1 [
0 => "10"
]
]
}
Note: The problem is when I click submit on pop modal it try to send the base form at first
What do I need to change to get what I want?
Note: The problem is when I click submit on pop modal it try to send the base form at first
It means laravel is treating your both form as one and when u try to submit the pop up form it submited the base form. Please make sure you both form are separated.
There might possible that u have not close one of the form tag and the save changes button of pop up form is acting as the base form submit button.

autocomplete and multiple function using ajax in laravel

I am new to laravel framework. I want to complete a important task in my app.
In that app they have modules like invoices,quotes,payment,customers. for particular customers they have multiple invoices with status of sent and partially paid.
Here is the receipt page, on type of customer name it will get autosuggestion from customer table. Onclick of cutomer name it will get invoice details from (invoice table) based on customer id,and need to show on table below that customer name textbox, onclick of table invoice it will open modal which means if the particular customer has unpaid invoice they need to record payment else proceed with normal receipt creation.
I try the code like this, But I am not getting proper output please anyone help me to get out of this issue.
<input type="text" name="customername" required="required" id="cust" placeholder="Customer Name" class="form-control col-md-7 col-xs-12 typeahead"/>
$( function() {
$( "#cust" ).autocomplete({
//source: "http://www.duminex.com/client/search",
source: "{{route('search.client')}}",
select: function( event, ui ) {
get_invoices(ui.item.id);
$('#id').val(ui.item.id);
$('#clientAddress').val(ui.item.address);
}
});
} );
function get_invoices(client_id)
{
$.ajax({
method: 'GET',
url: "{{route('client.details')}}"
}).done(function(data){
alert(data);
});
}
routes
Route::get('/client/search',[
'uses'=>'ClientsController#search',
'as'=>'search.client'
]);
Route::get('/client/search2', 'ClientsController#search2')->name('client.details');
Controller
public function search(Request $request)
{
$s= Input::get('term');
$clients = Client::select("id" ,"user_id", "companyname", "companyaddress" , "billingAddress")->where('companyname','like','%'.$s.'%')->where('user_id',Auth::user()->id)->get();
if(count($clients) == 0){
$searchResult[] = "No Item found";
}
else{
foreach ($clients as $key => $value) {
$searchResult[] = ['id' => $value->id, 'value' => $value->companyname , 'email' => $value->companyaddress , 'address' => $value->billingAddress];
}
}
return $searchResult;
}
public function search2(Request $request)
{
$clients = Invoice::select("invoiceNo")->where('status',['sent,Partially paid'])->where('client_id',$request->client_id)->get();
if(count($clients) == 0){
$searchResult[] = "No Item found";
}
else{
foreach ($clients as $key => $value) {
$searchResult[] = ['invoiceNo' => $value->invoiceNo];
}
}
return $searchResult;
}
Thanks in advance. Please anyone to help me get out of this issue.
You are not passing any data to the ajax so thats why you are not getting any result.
Try below code :
function get_invoices(client_id) {
$.ajax({
method: 'GET',
data : {
client_id: client_id
},
url: "{{route('client.details')}}"
}).done(function(data){
alert(data);
});
}

Saving multiple data dynamic form in Laravel 5.1 and Vue JS

I have to add/post data form. But the form dynamically can increase as user 'click' on a button. I've already browse about it and there some answer i get like using $request->all() to fetch all data from input forms.
And then my problem is, my app using VueJS as front-end. Is there any some configuration on VueJS script to post all data from that dynamic form??
My Blade template that will be increase dynamically:
<div id="form-message">
{!! Form::text('rows[0][DestinationNumber]', null, [
'id' => 'recipient',
'class' => 'form-control',
'v-model' => 'newMessage.DestinationNumber'
])
!!}
{!! Form::textarea('rows[0][TextDecoded]', null, [
'rows' => '3',
'id' => 'recipient',
'class' => 'form-control',
'v-model' => 'newMessage.TextDecoded'
])
!!}
</div>
That zero number will increase depends on how much user click add button.
And then here my VueJS script
var newSingleMessage = new Vue({
el: '#newsinglemsg',
data: {
newMessage: {
DestinationNumber: '',
TextDecoded: ''
},
},
methods: {
onSubmitForm: function(e) {
e.preventDefault();
var message = this.newMessage;
this.$http.post('api/outbox', message);
message = { DestinationNumber: '', TextDecoded: '' };
this.submitted = true;
}
}
});
On laravel controller, i have simple logic to test result how data passed.
$input = $request->all();
$output = dd($input);
return $output;
And, I test it using 2 additional form. So, the data should be 3 rows. The result (checked from FireBug) to be like this
{"DestinationNumber":"1234567890","TextDecoded":"qwertyuio"}
Data passed just one, and then the type is JSON. Even I use return $output->toArray(), type still JSON.
Oh yeah, once more. Idk how to make the zero number increase dynamically using javascript. When testing, i just manual add the form. Here my add click function javascript
var i = 0,
clone = $('#form-message').clone(),
recipient = document.getElementById('recipient');
recipient.setAttribute('name', 'rows['+ i +'][DestinationNumber]');
clone.appendTo('.form-message:last');
i++;
For second and next rows, name attribute not added on the input elements.
Thanks
You're mixing blade and jquery and vue in a way that is pretty confusing. Check out this JS fiddle that accomplishes all of this with Vue:
https://jsfiddle.net/cr8vfgrz/10/
You basically have an array of messages that are automatically mapped to inputs using v-for. As those inputs change, your messages array changes. Then when submit is pressed, you just post this.messages and the array of messages is sent to server. Then you can clear the array to reset the form.
Template code:
<div id="form-message">
<button class="btn btn-default" #click="addNewMessage">New Message</button>
<template v-for="message in messages">
<input type="text" v-model="message.DestinationNumber" class="form-control">
<textarea rows="3" v-model="message.TextDecoded" class="form-control"></textarea>
</template>
<button class="btn btn-success" #click.prevent="submitForm">Submit</button>
</div>
Vue code:
var newSingleMessage = new Vue({
el: '#form-message',
data: {
messages: [
{
DestinationNumber: '',
TextDecoded: ''
}
],
submitted:false
},
methods: {
addNewMessage: function(){
this.messages.push({
DestinationNumber: '',
TextDecoded: ''
});
},
submitForm: function(e) {
console.log(this.messages);
this.$http.post('api/outbox', {messages:this.messages})
.then(function(response){
//handle success
console.log(response);
}).error(function(response){
//handle error
console.log(response)
});
this.messages = [{ DestinationNumber: '', TextDecoded: '' }];
this.submitted = true;
}
}
});
Edit:
In the controller you can use $request->input('messages'); which will be the array of messages. You can insert multiple new Outbox model using:
Outbox::insert($request->input('messages'));
or
foreach($request->input('messages') as $message){
Outbox::create($message);
}

ion auth forgot password mail not received in mail account

In ion auth my forgot password mail sent successfully but not received in my email account...
I have searched many tutorials but can't find any solution.
Please Help me to solve this.
my email config file
$config['email_config'] = array(
'mailtype' => 'html',
'protocol' => 'smtp',
'smtp_host' => 'ssl://smtp.gmail.com',
'smtp_port' => '465',
'smtp_user' => 'k10kevalam#gmail.com',
'smtp_pass' => 'k10#kevalam',
);
in ion_auth config
$config['use_ci_email'] = TRUE; // Send Email using the builtin CI email class, if false it will return the code and the identity
$config['email_config'] = 'file';
in ion_auth.php library
if ($this->email->send())
{
echo $this->email->print_debugger();
$this->set_message('forgot_password_successful');
return TRUE;
}
display message :"email sent"
in my ion_auth.php controller
function forgot_password()
{
{
$this->form_validation->set_rules('email', $this->lang->line('forgot_password_username_identity_label'), 'required');
}
else
{
$this->form_validation->set_rules('email', $this->lang->line('forgot_password_validation_email_label'), 'required|valid_email');
}
if ($this->form_validation->run() == false)
{
//setup the input
$this->data['email'] = array('name' => 'email',
'id' => 'email',
);
if ( $this->config->item('identity', 'ion_auth') == 'username' ){
$this->data['identity_label'] = $this->lang->line('forgot_password_username_identity_label');
}
else
{
$this->data['identity_label'] = $this->lang->line('forgot_password_email_identity_label');
}
//set any errors and display the form
$this->data['message'] = (validation_errors()) ? validation_errors() : $this->session->flashdata('message');
$this->_render_page('auth/forgot_password', $this->data);
}
else
{
// get identity from username or email
if ( $this->config->item('identity', 'ion_auth') == 'username' ){
$identity = $this->ion_auth->where('username', strtolower($this->input->post('email')))->users()->row();
}
else
{
$identity = $this->ion_auth->where('email', strtolower($this->input->post('email')))->users()->row();
}
if(empty($identity)) {
if($this->config->item('identity', 'ion_auth') == 'username')
{
$this->ion_auth->set_message('forgot_password_username_not_found');
}
else
{
$this->ion_auth->set_message('forgot_password_email_not_found');
}
$this->session->set_flashdata('message', $this->ion_auth->messages());
redirect("auth/forgot_password", 'refresh');
}
//run the forgotten password method to email an activation code to the user
$forgotten = $this->ion_auth->forgotten_password($identity->{$this->config->item('identity', 'ion_auth')});
if ($forgotten)
{
//if there were no errors
$this->session->set_flashdata('message', $this->ion_auth->messages());
redirect("auth/login", 'refresh'); //we should display a confirmation page here instead of the login page
}
else
{
$this->session->set_flashdata('message', $this->ion_auth->errors());
redirect("auth/forgot_password", 'refresh');
}
}
}
What should i change.?
Your Help would Be Appreciated.
Thanks in Advance...
The best thing to do is just to create a test controller method that sends an email to work out the proper email settings.
made one email file and changing some security in gmail...
in my email config file
<?php
$config["mailtype"] = "html";
$config["protocol"] = "smtp";
$config["smtp_host"] = "ssl://smtp.googlemail.com";
$config["smtp_user"] = "xxxx#gmail.com";
$config["smtp_pass"] = "xxxx";
$config["smtp_port"] = 465;
$config["crlf"] = "\r\n";
$config["newline"] = "\r\n";
?>
suggest to made config file for email

Categories