x editable and codeigniter: display error message if data not updated into db - codeigniter

In my application I have a dataTable to display record from db, I am trying to edit record using x-editable and its working fine. But the problem is I want to display an error message if submitted data not updated successfully into the db.
I tried 'success:' but it triggered after submit the form whatever the data reach the db or not, but i want to trigger the success if controller return true.
Thanks

if you are processing the editable submission using ajax you need to set:
echo 1; //if model returns true
and
echo 0; //if model returns false
in the controller.
Then in the ajax reponse you need to check in the script:
(Consider the response variable is response)
if(response==1)
{
alert('Update Success.');
}
else
{
alert('Update Failure !')
}

This would be easier if you provided us with a code sample.
If you're working with ActiveRecord, you can always use:
if($this->db->affected_rows() > 0)
{
return true;
}
else
{
return false;
}

Related

Why Laravel accessor fires on insert?

I'm not sure how they work, I was thinking that accessor fires when you access the attribute, however when I try to insert new record my accessor fires. I store in my database only image_name by removing URL and I use an accessor to include my URL route when I retrieve my image name. I found out that my accessor fires on insert and change my input:
ImageRepository.php
public function save($imageData)
{
$this->model->owner()->associate(auth()->user());
$this->model->type = $imageData->type;
$this->model->image_name = $imageData->image_url;
$this->model->save();
return $this->model;
}
Image.php
public function getImageNameAttribute($value)
{
$filePath = 'my_path';
// check if method was hit
logger()->info('getImageNameAttribute: '.$value);
// return default image if not found
if ($value == '' || $value == null || Str::contains($value, 'no-image.png') || !File::exists(public_path($filePath))) {
return asset('img/no-image.png');
} else {
return asset($filePath);
}
}
Input for $imageData->image_url:
https://some-random-image-url/image-name.jpg
Inserted data:
img/no-image.png
Excepted output (I have a function that extracts the name from URL):
image-name.jpg
When I check the log, I get the message:
getImageNameAttribute: https://some-random-image-url/image-name.jpg
Can someone explain to me if I'm doing something wrong or this is working as pretended?
I did solve the problem, I miss checked. Actually inserted record in my database is correct:
image-name.jpg
But I was checking dd() output after the insert and the value from there was not correct:
img/no-image.png
Because when dd() fires, the accessor is also fired (as we are retrieving data) and as the image was not downloaded it was actually showing correct data.

Yii2 validation on controller action

I am developing a Yii 2.0 application in which users can create orders then send the orders to review and after that it follows a number of stages in the workflow.
Everything is ok until yesterday that the customer ask for the possibility that before sending the orders to review the order are considered as draft. Which means I have to turn off validations on create and validate them when users clicks Send To Review button. I know Yii 2.0 supports scenarios but maybe scenarios doesn't apply to this because the Send To Review button is shown in a readonly view. This forces me to do validation inside the controller action because there is no send_to_review view. How can this be done (I mean model validation inside controller action)?
Here is the controller action code
public function actionSendToReview($id)
{
if (Yii::$app->user->can('Salesperson'))
{
$model = $this->findModel($id);
if ($model->orden_stage_id == 1 && $model->sales_person_id == Yii::$app->user->identity->id)
{
$model->orden_stage_id = 2;
$model->date_modified = date('Y-m-d h:m:s');
$model->modified_by = Yii::$app->user->identity->username;
//TODO: Validation logic if is not valid show validation errors
//for example "For sending to review this values are required:
//list of attributes in bullets"
//A preferred way would be to auto redirect to update action but
//showing the validation error and setting scenario to
//"send_to_review".
$model->save();
$this::insertStageHistory($model->order_id, 2);
return $this->redirect(['index']);
}
else
{
throw new ForbiddenHttpException();
}
}
else
{
throw new ForbiddenHttpException();
}
}
What I need to solve is the TODO.
Option 1: Showing validation errors in the same view and the user has to clic Update button change the requested values save and then try to Send To Review again.
Option 2: Redirecting automatically to update view already setting scenario and validation errors found in the controller.
Thanks,
Best Regards
You can use $model ->validate()for validation in controller.
public function actionSendToReview($id)
{
if (Yii::$app->user->can('Salesperson'))
{
$model = $this->findModel($id);
if ($model->orden_stage_id == 1 && $model->sales_person_id == Yii::$app->user->identity->id)
{
$model->orden_stage_id = 2;
$model->date_modified = date('Y-m-d h:m:s');
$model->modified_by = Yii::$app->user->identity->username;
//TODO: Validation logic if is not valid show validation errors
//for example "For sending to review this values are required:
//list of attributes in bullets"
//A preferred way would be to auto redirect to update action but
//showing the validation error and setting scenario to
//"send_to_review".
//optional
$model->scenario=//put here the scenario for validation;
//if everything is validated as per scenario
if($model ->validate())
{
$model->save();
$this::insertStageHistory($model->order_id, 2);
return $this->redirect(['index']);
}
else
{
return $this->render('update', [
'model' => $model,
]);
}
}
else
{
throw new ForbiddenHttpException();
}
}
else
{
throw new ForbiddenHttpException();
}
}
If you don't need validation in actionCreate().Create a scenario for not validating any field and apply there.

Clearing Flash Message in CakePHP 3.1.1

I'm trying to clear a Flash Message in CakePHP 3.1.1
I have a function when a user logs in, if his customer data is not complete, he is redirected to a form to complete it. That looks like this:
public function index()
{
//Some code to check whether the customers profile is complete
//If it's not complete, then redirect to the "complete" action with a flash message
if($completion == 0){
$this->Flash->success(__('Please complete your customer profile data.'));
$this->setAction('complete', $custid);
//Otherwise go to their view
} elseif ($completion == 1){
$this->setAction('view', $custid);
}
}
This works fine, and user is redirected to the Complete action/Form with the Flash Message.
Then the Complete action looks like this:
public function complete($id = null)
{
//Get all the customer data input
if ($this->request->is(['patch', 'post', 'put'])) {
$customer = $this->Customers->patchEntity($customer, $this->request->data);
//Set the completion status to complete (1)
$customer->completion_status = 1;
if ($this->Customers->save($customer)) {
$completion = 1;
$this->set('completion', $completion);
//After the Save, redirect to the View action with a new Flash Message
$this->Flash->set(__('Your customer information is complete and has been saved!',['clear'=>'true']));
return $this->redirect(['action' => 'view',$custid]);
} else {
$this->Flash->error(__('The customer could not be saved. Please, try again.'));
}
}
$this->set(compact('customer'));
$this->set('_serialize', ['customer']);
}
It work fine BUT: When the user is redirected to the View action with the Success Flash after saving their data, the Flash from the Index (telling them 'Please complete your customer profile data.') still shows up again.
If the user refreshes on the view, then both Flash messages go away as they should.
How can I clear that initial Flash message when redirecting? I've tried using the clear key but it seems to not be working.
Any advice is greatly appreciated!
Thanks,
DBZ
You can add this in the beginning of your action
$this->request->session()->delete('Flash');
to delete more specific you can do e.g. to delete only the messages from AuthComponent
$this->request->session()->delete('Flash.auth');
One more thing:
you can handle which flash-messages are displayed in the view like:
this->Flash->render('auth');
or
this->Flash->render('error');
If you don't display a flash-message its kept in the session until you display it somewhere or remove it from session.
Flash message are stored in session, so just clear the relevant session key: $this->Session->delete('Flash.flash') or $this->Session->delete('Flash')
Check to make sure that you aren't always getting $completion == 0 (which could match FALSE as well).
I suspect this is why your flash message is always showing.
Cake will automatically delete a flash message after it displays it.
Apparently you are passing a string to clear instead of a boolean:
New in version 3.1: A new key clear was added. This key expects a bool and allows you to delete all messages in the current stack and start a new one.
Try setting true without the quotation marks:
$this->Flash->set(__('Your customer information is complete and has been saved!'),[
'clear'=> true
]);
New in version 3.1: Flash messages now stack. Successive calls to set() or __call() with the same key will append the messages in the $_SESSION. If you want to keep the old behavior (one message even after consecutive calls), set the clear parameter to true when configuring the Component.
Use like this:
$this->loadComponent( 'Flash', ['clear' => true] );

handling database error with ajax request codeigniter

I am intentionally making error i.e. using one of the coulmn's name wrong to learn how to handle the error with ajax call with codeigniter.
Last Comment in controller function at the end is my question/problem
My AJX Code is following. I am using ajaxform plugin. It shows me all response from controller perfectly but problem is only I am unable to get response from model in controller while using ajax call that is little weird
$('#myForm').ajaxForm
({
success: function(responseText)
{
if(responseText != "1")
$('#feedback').html(responseText);
}
});
Following is snapshot of exact error which i can see in console but unable to get in controller and hence in view. It describes complete error i.e unknown column in given query, but i captured only upper portion.
My model function is below
public function updateItem($id, $data, $tbl)
{
$this->db->where('id', $id);
$r = $this->db->update($tbl, $data);
if($r)
return $r;
else
{
$r = $this->db->_error_message();
return $r;
}
}
My controller function code
public function upadteme()
{
$r = $this->ajax_model->updateItem($uid, $data, 'users');
echo $r." -- "; // Unable to get this echo working
//when using ajaxcall (calling controller through ajax) otherwise fine
}
It looks like the class will not populate _error_message if db_debug is on which it appears to be by default.
In config/database.php, set
$db['default']['db_debug'] = FALSE;
and try again.

CodeIgniter - showing original URL of index function?

I'm not sure if I'm approaching this fundamentally wrong or if I'm just missing something.
I have a controller and within it an index function that is, obviously, the default loaded when that controller is called:
function index($showMessage = false) {
$currentEmployee = $this->getCurrentEmployee();
$data['currentEmp'] = $currentEmployee;
$data['callList'] = $currentEmployee->getDirectReports();
$data['showMessage'] = $showMessage;
$this->load->view('main', $data);
}
I have another function within that controller that does a bulk update. After the updates are complete, I want the original page to show again with the message showing, so I tried this:
/**
* Will save all employee information and return to the call sheet page
*/
function bulkSave() {
//update each employee
for ($x = 0; $x < sizeof($_POST['id']); $x++) {
$success = Employee::updateEmployeeManualData($_POST['id'][$x], $_POST['ext'][$x], $_POST['pager'][$x], $_POST['cell'][$x], $_POST['other'][$x], $_POST['notes'][$x]);
}
$this->index($success);
}
What is happening is that the original page is accessed using:
localhost/myApp/myController
after the bulk update it is showing as:
localhost/myApp/myController/bulkSave
when I really want it to show the url as the index page again, meaning that the user never really sees the /bulkSave portion of the URL. This would also mean that if the user were to refresh the page it would call the index() function in the controller and not the bulkSave() function.
Thanks in advance.
Is this possible?
You are calling your index() funciton directly, within bulkUpdate() hence the uri does not change back to index because you are not making a new server request, you are just navigating within your controller class.
I usually use the same Controller function for tasks like this, directing traffic based on whether or not $_POST data has been passed or not like this...
function index() {
if($_POST) {
//process posted data
for ($x = 0; $x < sizeof($_POST['id']); $x++) {
$data['showMessage'] = Employee::updateEmployeeManualData($_POST['id'][$x], $_POST['ext'][$x], $_POST['pager'][$x], $_POST['cell'][$x], $_POST['other'][$x], $_POST['notes'][$x]);
}
}
else {
//show page normally
$data['showMessage'] = FALSE;
}
//continue to load page
$currentEmployee = $this->getCurrentEmployee();
$data['currentEmp'] = $currentEmployee;
$data['callList'] = $currentEmployee->getDirectReports();
$this->load->view('main', $data);
}
Then if it is a form that you are submitting, just point the form at itself in your view like this...
<?= form_open($this->uri->uri_string()) ?>
This points the form back at index, and because you are posting form data via $_POST it will process the data.
I usually do a redirect to the previous page as it prevent users to refresh (and submit twice) their data.
You can use the redirect() helper function of CI.
http://codeigniter.com/user_guide/helpers/url_helper.html (at the bottom)

Resources