I want to delete the selected record from database - php

I have two form views: form and controller.
Below are the codes which I want to delete the selected record from database using codeginiter.
Please check why code.controller form is not working.
view Form
function deleteCustEntry(id){
var answer = confirm("Are you sure you want to move in trash?")
if (answer){
$.ajax({
type: 'POST',
url: '<?php echo base_url();?>manager/deletecust/',
data: { manager_id: id, status : 'trash'},
}
}
Controller form
public function deletecust() {
$manager_id = $this->input->post('manager_id');
$status = $this->input->post('status');
$result = 0;
if($status == 'trash') {
$data = array(
'isTrash' => 1
);
$this->db->where('id', $manager_id);
$this->db->update('manager', $data);
$result = 1;
} elseif ($status == 'delete'){
$this->db->delete('manager', array('id' => $manager_id));
if ($this->db->affected_rows() > 0) {
$result = 1;
}
}
echo $result;
flush();
}

do you want to delete the record from the table or change the status of the record. As status : 'trash' this will always change the status of isTrash. Provide more info.

Related

Automatically filling in sql column data after referencing a substring of another column

Currently I'm using Mysql and CodeIgniters MVC framework to fill in my data. The table logs every status change that has been made and when it was made. This is what the database currently looks like:
I've added new columns in the table called status_from and status_to, where I want these columns to take the substring from action column.
But now how do I display it in my database with my following code:
Controller class:
public function status($status){
$statusar = array('D'=>'Draft','N'=>'Unpublish','Y'=>'Publish','U'=>'Action','L'=>'Unlisted','S'=>'Sold','T'=>'Let');
if($this->input->post('id')){
foreach($this->input->post('id') as $key => $id):
$check = $this->listings_model->loadlisting_check($id);
$log = "Listing website status changed from ". $statusar[$check->status]." to ".$statusar[$status].". The listing ID is #".$id.".";
$this->logs_model->insert_log(array('refno'=>$check->refno,'action'=>trim($log)));
$data=array('status'=>$status);
if($status == 'T' || $status == 'Y' || $status == 'S'){
$pub = 1;
}else{
$pub =0;
}
$this->listings_model->lpupdate(array('property_publish'=>$pub),$id);
endforeach;
}
return true;
}
listings_model:
function loadlisting_check($id)
{
$this->db->select("refno, status, archive");
$id=$this->db->escape_str($id);
$cond=array("$this->table_name.$this->primary_key"=>$id);
$this->db->where($cond);
$this->db->from($this->table_name);
$query = $this->db->get();
return $query->row();
}
logs_model:
public function insert_log($log)
{
$log['agent_id'] = $this->session->userdata('clientsessuserid');
$log['logtime'] = date('Y-m-d H:i:s');
$this->db->insert($this->table_name, $log);
return true;
}
Basically I want to fill my status_from column with $statusar[$check->status] and status_to column with $statusar[$status] when every new entry is made
You can pass the variables you want to add in the array in insert_log method parameter with proper key matched with column name in your table
public function status($status){
$statusar = array('D'=>'Draft','N'=>'Unpublish','Y'=>'Publish','U'=>'Action','L'=>'Unlisted','S'=>'Sold','T'=>'Let');
if($this->input->post('id')){
foreach($this->input->post('id') as $key => $id):
$check = $this->listings_model->loadlisting_check($id);
$log = "Listing website status changed from ". $statusar[$check->status]." to ".$statusar[$status].". The listing ID is #".$id.".";
$this->logs_model->insert_log(array('refno'=>$check->refno,'action'=>trim($log) , 'status_from'=>$statusar[$check->status] ,'status_to'=>$statusar[$status]));
$data=array('status'=>$status);
if($status == 'T' || $status == 'Y' || $status == 'S'){
$pub = 1;
}else{
$pub =0;
}
$this->listings_model->lpupdate(array('property_publish'=>$pub),$id);
endforeach;
}
return true;
}
And you will not need to add anything else to your model

Codeigniter on duplicate key insert

i want to create a condition which a user would choose whether he wants to use an input which means a database would create an auto_incremented id or he wants to use an older data which will not use new id but only use it. i have used dropdown database populate for my old input.
My Dropdown list
//get contractor list
$Contractor_List = $this->foo_pro->get_list_contractors();
$opt = array('' => '');
foreach ($Contractor_List as $Contractor_No) {
$opt[$Contractor_No] = $Contractor_No;
}
$data['con_list'] = form_dropdown('',$opt,'','ProjectID = "Contractor_No" name="contractorNo" id="" class="w3-select w3-border w3-hover-light-grey"');
My Controller
public function save_createdProject()
{
$data_project = array();
$data_contractor = array();
//project data
if ($this->input->post('year') === '') {
$data_project['P_Year'] = 15;
}else{
$data_project['P_Year'] = $this->input->post('year');
}
if ($this->input->post('code') === '') {
$data_project['Code'] = 'KO';
}else{
$data_project['Code'] = $this->input->post('code');
}
$data_project['ProjectID'] = $this->input->post('project');
$data_project['Contract_Amount'] = $this->input->post('camount');
//contractor data
if ($this->input->post('cname') === '' && $this->input->post('caddress') === '') {
$data_project['Contractor_No'] = $this->input->post('contractorNo');
}else{
$data_contractor['Contractor_Name'] = $this->input->post('cname');
$data_contractor['Contractor_Address'] = $this->input->post('caddress');
}
$this->foo_pro->add_project($data_project, $data_contractor);
redirect('Main/project','refresh');
//var_dump($data);exit;
}
My Model
public function add_project($data_project, $data_contractor)
{
//contractor
$this->db->insert('contractor', $data_contractor);
$Contractor_No = $this->db->insert_id();
//project
$data_project['Contractor_No'] = $Contractor_No;
$this->db->insert('project', $data_project);
$ProjectID = $this->db->insert_id();
}
this here is my problem except inserting the older data which is the contractor_no 1 it creates another data that would insert as contractor_no 4.. but also i need to insert new data for new contractor_name..

vTiger Custom Field Validation beforesave

I have created a custom module on vTiger 6.5.
I have made an event handler for the module but I am wondering how I could perform some sort of validation on this field. So fat I have done this but I am unable to get it work, I have tested the handler just echoing a sting and it works fine.
Please see my code below. Thanks!
<?php
/*+***********************************************************************************
* The contents of this file are subject to the vtiger CRM Public License Version 1.0
* ("License"); You may not use this file except in compliance with the License
* The Original Code is: vtiger CRM Open Source
* The Initial Developer of the Original Code is vtiger.
* Portions created by vtiger are Copyright (C) vtiger.
* All Rights Reserved.
*************************************************************************************/
# getModuleName : Returns the module name of the entity.
# getId : Returns id of the entity, this will return null if the id has not been saved yet.
# getData : Returns the fields of the entity as an array where the field name is the key and the fields value is the value.
# isNew : Returns true if new record is being created, false otherwise.
# 'vtiger.entity.beforesave.modifiable' : Setting values : $data->set('simple_field', 'value');
class isaHandler extends VTEventHandler {
function handleEvent($eventName, $entityData) {
global $adb;
$moduleName = $entityData->getModuleName();
if($moduleName=='isa'){
if($eventName == 'vtiger.entity.beforesave.modifiable') {}
if($eventName == 'vtiger.entity.beforesave') {
if('currentamount' > 20000){
echo "Please go back and enter less than 20000";
exit;
}
}
if($eventName == 'vtiger.entity.beforesave.final') {}
if($eventName == 'vtiger.entity.aftersave') {
}
}
}
}
?>
After doing some searching around and looking at other peoples event handlers I managed to solve this by changing:
if($eventName == 'vtiger.entity.beforesave') {
if('currentamount' > 20000){
echo "Please go back and enter less than 20000";
exit;
}
to
if($eventName == 'vtiger.entity.beforesave') {
$price = $entityData->get('currentamount');
if($price > 20000){
echo "Please go back and enter less than 20000";
exit;
}
Now I want to see if I can display the message and then give a link to go back to the entity module with all the fields still full.
In my opinion you should use the recordPreSave function.
It's allow you to display an information/error message before to save data on the database
Here is an example:
In your Edit.js:
donCache : {},
checkDon : function(details) {
// alert("checkOverlap");
var aDeferred = jQuery.Deferred();
var params = {
'module' : 'Affectations',
'action' : "checkAffectAmount",
'mode': 'CtrlAffectAmount',
'recordId' : details.don,
'montant' : details.montant
}
AppConnector.request(params).then(
function(data) {
if (data.success == true) {
// console.log(data.result);
var statut = data.result.statut;
var reste = data.result.reste;
if(statut == "error"){
aDeferred.reject(data);
}else {
aDeferred.resolve(data);
}
}
},
function(error,err){
aDeferred.reject();
}
);
return aDeferred.promise();
},
registerRecordPreSaveEvent : function(form) {
var thisInstance = this;
if (typeof form == 'undefined') {
form = this.getForm();
}
form.on(Vtiger_Edit_Js.recordPreSave, function(e, data) {
var check = false;
var recordId = jQuery('input[name="record"]').val();
if (!recordId || recordId) {
var montant_affectation = jQuery("input[name='affectations_montant']").val();
var don_id = jQuery("input[name='affectations_potentialid']").val();
var params = {};
if (!(check in thisInstance.donCache)) {
thisInstance.checkDon({
'montant' : montant_affectation,
'don': don_id
}).then(
function(data){
thisInstance.donCache[check] = data['success'];
form.submit();
},
function(data, err){
thisInstance.donCache[check] = data['success'];
var reste = data.result.reste;
var msg = app.vtranslate("<strong>Attention!</strong> La somme des affectations est supérieure de ")+ reste +app.vtranslate(" Euros au montant du don");
Vtiger_Helper_Js.showPnotify(msg);
delete thisInstance.donCache[check];
}
);
} else {
delete thisInstance.donCache[check];
return true;
}
e.preventDefault();
}
})
},
The PHP part in modules/isa/actions:
<?php
/***********************************
** DEBUT ALTAIR - JPR 15/06/2016 ***
***********************************/
class Affectations_checkAffectAmount_Action extends Vtiger_Action_Controller {
function __construct() {
$this->exposeMethod('CtrlAffectAmount');
}
public function checkPermission(Vtiger_Request $request) {
$moduleName = $request->getModule();
$moduleModel = Vtiger_Module_Model::getInstance($moduleName);
$userPrivilegesModel = Users_Privileges_Model::getCurrentUserPrivilegesModel();
$permission = $userPrivilegesModel->hasModulePermission($moduleModel->getId());
if(!$permission) {
throw new AppException('LBL_PERMISSION_DENIED');
}
}
public function process(Vtiger_Request $request) {
$mode = $request->getMode();
if(!empty($mode) && $this->isMethodExposed($mode)) {
$this->invokeExposedMethod($mode, $request);
return;
}
}
function CtrlAffectAmount(Vtiger_Request $request){
global $adb,$log;
$log->debug("ALTAIR CtrlAffectAmount OK");
$recordId = $request->get('recordId');
$montant = $request->get('montant');
// $query = $adb->pquery("SELECT SUM(unit_price) AS sommeaffectation FROM vtiger_products INNER JOIN vtiger_crmentity ON vtiger_products.productid = vtiger_crmentity.crmid WHERE don_affecte = ? AND vtiger_crmentity.deleted=0",array($recordId));
$query = $adb->pquery("SELECT SUM(affectations_montant) AS sommeaffectation FROM vtiger_affectations INNER JOIN vtiger_crmentity ON vtiger_affectations.affectationsid = vtiger_crmentity.crmid WHERE vtiger_affectations.affectations_potentialid = ? AND vtiger_crmentity.deleted=0",array($recordId));
$sommeAffectation = $adb->query_result($query,0,"sommeaffectation");
$query = $adb->pquery("SELECT amount FROM vtiger_potential INNER JOIN vtiger_crmentity ON vtiger_potential.potentialid = vtiger_crmentity.crmid WHERE potentialid = ? AND vtiger_crmentity.deleted = 0", array($recordId));
$montantDon = $adb->query_result($query,0,"amount");
if ( ($sommeAffectation + $montant) == $montantDon) {
$statut = "ok";
$reste = "";
} else if( ($sommeAffectation + $montant) > $montantDon) {
$statut = "error";
$reste = ($sommeAffectation + $montant) - $montantDon;
}
$value = array('statut'=>$statut, 'reste'=>$reste);
$response = new Vtiger_Response();
$response->setEmitType(Vtiger_Response::$EMIT_JSON);
$response->setResult($value);
$response->emit();
}
}
Oh. you have 1 invalid error here. please change:
if($eventName == 'vtiger.entity.beforesave') {
$currentAmount = $entityData->get('currentamount');
if($currentAmount > 20000){
echo "Please go back and enter less than 20000";
exit;
}
}

Load additional data into the view

I have this PHP code where I am loading a quiz into the view. When I select and submit an answer the view is changed and displays only the correct message or the wrong one.
What I am trying to achieve is when clicking the submit button for the answer, to keep the question and just display under if correct or not.
This is the code that I have:
function guess()
{
$guess = $this->input->get('name',false);
$personid = $this->input->get('id',false);
if ($guess === null) {
$newguess['data'] = $this->Starmodel->getQuestion();
$this->load->view('starview',$newguess);
}
else {
$res= $this->Starmodel->isCorrectAnswer($personid,$guess);
$person = $this->load->view('starview', array('iscorrect' => $res,
'name' => $guess));
}
}
My main view is starview.php. Can I use divs and target a specific load a view inside the specific div? How can I do this?
Thank you
Let say this your startview view...
//Your question goes here
//Answer part
<?php if($this->input->post()):
echo $answer_view_data
endif; ?>
In your function guess()
function guess()
{
$guess = $this->input->get('name',false);
$personid = $this->input->get('id',false);
if ($guess === null) {
$newguess['data'] = $this->Starmodel->getQuestion();
$this->load->view('starview',$newguess);
}
else {
$res= $this->Starmodel->isCorrectAnswer($personid,$guess);
$answer_data = 'Sample answer data';
$person = $this->load->view('starview', array('iscorrect' => $res,
'name' => $guess, 'answer_data' => $answer_data));
}
}

Data from a single column of a sql view not displayed

I have a SQL view in phpmyadmin which has a is used to populate data in a table created using jquery jtable. The issue is quite bizarre as only one column's data which is being pulled by the view isn't being displayed and all of the others are being displayed without an issue. There is also no issue when I edit the fields and I can see the changes I made in phpmyadmin. How do I get the Successful column to display ? All help is greatly appreciated.
Screenshot of the table
js which handles creation of the table
function getLessonsLearnedResponseChildTable(ContainerID) {
var table = {
title: '',
width: '5%',
sorting: false,
edit: false,
create: false,
display: function(data) {
//create an image to be used to open child table
var $img = $('<img src="' + config.base_url + 'assets/images/expand_row-small.png" title="View Responses" style="height:30px;width:30px;cursor:pointer;" height="30" width="30"/>');
$img.click(function() {
$('#' + ContainerID).jtable('openChildTable',
$img.closest('tr'),
{
title: data.record.event,// + ' - Response Plans'
actions: {
listAction: config.base_url + "data_fetch/responses/" + data.record.risk_id,
deleteAction: config.base_url + 'data_fetch/delete_response/',
updateAction: config.base_url + 'data_fetch/edit_response/'
},
messages: defaultResponseMessages,
fields: LessonsLearnedResponseFields
}, function(data) {//opened handler
data.childTable.jtable('load');
});
});
//return image to show on row
return $img;
}
};
return table;
}
Controller method for the listAction:
function responses($risk_id = null, $offset = 0, $limit = 100, $order_by = 'response_id', $direction = 'ASC') {
$confirm_member = $this->User_model->confirm_member(true, false);
if (!$confirm_member['success']) {
$this->print_jtable_error(self::ERROR_NOT_LOGGED_IN);
return;
}
$user_id = $_SESSION['user_id'];
$this->load->model('Response_model');
$responses = $this->Response_model->get_all($risk_id, $user_id, $limit, $offset, $order_by, $direction);
if ($responses == false) {
$this->print_jtable_error(self::ERROR_NO_ACCESS_PERMISSION);
return;
} else {
return $this->print_jtable_result($responses);
}
}
get_all method in Response Model
/*
* Retrieves all responses associated with the risk
*/
public function get_all($risk_id, $user_id, $limit = null, $offset = 0, $order_by = null, $direction = 'ASC') {
//load risk model to check if user can read from project
$this->load->model('Risk_model');
if ($this->Risk_model->initialize($risk_id, $user_id) == false) {
return false;
}
if ($limit !== null && $limit != 0) {
$this->db->limit($limit, $offset);
}
if ($order_by !== null) {
$this->db->order_by($order_by, $direction);
}
$query = $this->db->select('SQL_CALC_FOUND_ROWS *', false)->from('view_responses')->where('risk_id', $risk_id)->get();
$data = $query->result_array();
$this->load->model('Task_model');
foreach ($data as &$response)
$response['WBS'] = $this->Task_model->normalize_WBS($response['WBS']);
$data['num_rows'] = $this->db->
query('SELECT FOUND_ROWS()', false)->row(0)->{'FOUND_ROWS()'};
return $data;
}
Screenshot of the sql view
successful is received but not displayed
http://imgur.com/MqCVAGm
I've been able to solve the problem. It was an issue with spelling. I had a missing c in successful coming from the SQL view and now its working fine.

Categories