So I'm creating an application for clients to fill in an order to calculate the price. The client has to fill in a form, the form will be posted to a table in MySQL. When the order is complete the client gets an overview of his order with the calculated price. I'm having trouble with storing a variable (from tblPanel_Prices) which is related with a variable in tblPaneltypes. So after filling in the form data from column tblPaneltypes and tblPanel_Prices should be stored together in another table. Both tables (types and prices) are related.
The client has to select a type of panel. These types are stored in the table (tblPaneltypes). Every panel has a certain price-categorie (field price_id) which is needed to calculate the price. The prices of the paneltypes are stored in another table (tblPanel_Prices). There is a relation between the tblPaneltypes and tblPanel_Prices (both integer)
So the client fills in the form and selects a certain type of panel, this gets posted (controller) to the table with the function: this->input->post('paneltype').
After this I want to calculate the surface of the panel and make select the right price-category on the field price-id.
So in the form there is a type of panel choosen by the client. This already goes to my table, but I also want to pass the price_id tag in the form.
Then, I would like to get the price_id tag from the table tblPaneltypes to link this with the price_id tag in tblPanel_Prices. The value of the price_id isn't important for the client, so no need to select or show this value. I just need it to calculate the price of the panel (which depends on the type of panel filled in by the client)
Thanks in advance!
Store function in controller
public function store()
{
$this->load->model("orders/panels/Panels");
$this->form_validation->set_rules('amount', 'aantal', 'numeric|required|max_length[2]');
$this->form_validation->set_rules('dwidth', 'paneelbreedte', 'numeric|callback_check_width');
$this->form_validation->set_rules('dheight', 'paneelhoogte', 'numeric|callback_check_height');
$this->form_validation->set_rules('paneltype', 'paneeltype', 'required');
$this->form_validation->set_rules('ral_code', 'ral kleur', 'callback_check_double');
if ($this->auth()) {
if ($this->form_validation->run() == FALSE) {
$this->read_panel();
} else {
$panel = $this->Panels->create__entry(
$this->input->post('order_id'),
$this->input->post('amount'),
$this->input->post('dwidth'),
$this->input->post('dheight'),
$this->input->post('paneltype'),
$this->input->post('panelcategory'),
$this->input->post('color'),
$this->input->post('othercolor'),
$this->input->post('tubes'),
$this->input->post('colorswatch'),
$this->input->post('structurepaint'),
$this->input->post('uv'),
$this->input->post('window'),
$this->input->post('paintwindow'),
$this->input->post('windowsetup'),
$this->input->post('glastype'),
$this->input->post('door')
);
redirect("rail/read_rail?order=" . $this->input->post('order_id'));
}
} else {
login();
}
create__entry in model: at this moment I'm filling in the panelcategory manually in the model in. In the future it should filled in automaticly.
function create__entry($order_id, $amount, $dwidth,
$dheight, $paneltype, $panelcategory, $color,
$othercolor, $tubes,
$colorswatch, $structurepaint,
$uv, $windowtype, $paintwindow,
$windowsetup, $glastype, $door)
{
$this->order_id = $order_id;
$this->amount = $amount;
$this->dwidth = $dwidth;
$this->dheight = $dheight;
$this->paneltype = $paneltype;
$this->panelcategory = $panelcategory;
$this->color = $color;
$this->othercolor = $othercolor;
$this->tubes = $tubes;
$this->colorswatch = $colorswatch;
$this->structurepaint = $structurepaint;
$this->uv = $uv;
$this->windowtype = $windowtype;
$this->paintwindow = $paintwindow;
$this->windowsetup = $windowsetup;
$this->glastype = $glastype;
$this->door = $door;
$this->db->insert(self::TABLE_NAME, $this);
return $this->read__entry($this->db->insert_id());
}
Related
Currently I have a refno. column in my database with the format LP00001. Now I have a add page that inserts all data that the user inserts in the input field and all this data gets sent to a table in my database, but my refno column stays null which I want to have an auto incrementing value where the last 5 digits will be +1 everytime the user submits the form.
I do not want to have it be shown before the submit button as 2 users can be on that page at the same time which means they both will get the same id which means it has to generate it only at the time of submit. Currently this is my code:
Controller class:
if ($this->form_validation->run() == FALSE)
{
$main['page'] = 'crm/listings/add';
$this->load->view('crm/index', $main);
}else {
$maindata=array('clients_id'=>$this->session->userdata('clientsessid'),
'property_for'=>$this->security->xss_clean($this->input->post('property_for')),
'property_type'=>$this->security->xss_clean($this->input->post('property_type')));
$insertid=$this->listings_model->insert_listing($maindata);
if($insertid){
$this->session->set_flashdata('message', '<div>Successfully</div>');
redirect('listings/sales');
Model Class:
function insert_listing($maindata){
$this->db->insert("crm_listings",$maindata);
$prime=$this->db->insert_id();
return $prime;
}
So I assume I'll need to do this in my model class function insert_listing since that is called when I press submit button. Here another thing will be that the model will have to check what was the last entry in the database that has to be incremented for which I'm assuming I'll have to use echo str_replace("LP","","LP00001");
I guess you just have to prepend the initials LP to the returned autoIncremented id.
function insert_listing($maindata){
// ...
$this->db->set("refno", "LP". sprintf('%05d', $prime));
$this->db->where('id', $prime);
$this->db->update("crm_listings");
return $prime;
}
In Suitecrm/SugarCRM 6.5
I need to modify the ListView. Showing the value of a field based on a certain condition.
In the Account module, the name field may be empty based on certain conditions, I require that when this occurs show the value of a custom field. To do this, first I tryied using 'customCode' + smarty as usual in Edit/Detail vies, but in several posts mention that this is not possible in the ListView. The concession is to use logic hooks + a non-db field to store the calculated field. Following this SO answer I have written the following:
Custom field at custom/Extension/modules/Accounts/Ext/Vardefs/custom_field_name_c.php
<?php
$dictionary['Account']['fields']['name_c']['name'] = 'account_name_c';
$dictionary['Account']['fields']['name_c']['vname'] = 'LBL_ACCOUNT_NAME_C';
$dictionary['Account']['fields']['name_c']['type'] = 'varchar';
$dictionary['Account']['fields']['name_c']['len'] = '255';
$dictionary['Account']['fields']['name_c']['source'] = 'non-db';
$dictionary['Account']['fields']['name_c']['dbType'] = 'non-db';
$dictionary['Account']['fields']['name_c']['studio'] = 'visible';
Label at suitecrm/custom/Extension/modules/Accounts/Ext/Language/es_ES.account_name_c.php
<?php
$mod_strings['LBL_ACCOUNT_NAME_C'] = 'Nombre de cuenta';
Logic hook entry at custom/modules/Accounts/logic_hooks.php
$hook_array['process_record'] = Array();
$hook_array['process_record'][] = Array(
2,
'Get proper name',
'custom/modules/Accounts/hooks/ListViewLogicHook.php',
'ListViewLogicHook',
'getProperName'
);
Logic hook at custom/modules/Accounts/hooks/ListViewLogicHook.php
<?php
class ListViewLogicHook
{
public function getProperName(&$bean, $event, $arguments)
{
if (empty($bean->fetched_row['name'])) {
$bean->account_name_c = $bean->fetched_row['person_name_c'];
} else {
$bean->account_name_c = $bean->fetched_row['name'];
}
// Here I also tried, but same result
// $bean->account_name_c = empty($bean->name) ? $bean->person_name_c : $bean->name;
}
}
listviewdefs.php at custom/modules/Accounts/metadata/listviewdefs.php
I added the field
'NAME_C' =>
array (
'width' => '20%',
'label' => 'LBL_ACCOUNT_NAME_C',
'default' => true,
),
After these modifications and repair I hope to see the field full with the right value. But it appears empty. I have verified that the logic hook is properly called, but the name andperson_name_c fields are always empty. In case it is relevant I have verified in Studio that the name fields in Account is typename I do not know what this means when it comes to obtaining its value.
I appreciate your comments
The problem is in the logic hook is due to first that the $bean does not have access to the custom fields, so I have to invoke them using $bean->custom_fields->retrieve(); Also the name field is always empty, I had to use DBManager to get only the name field.
The logic of the final logic hook is the following:
<?php
class ListViewLogicHook
{
public function getProperName($bean, $event, $arguments)
{
// Get access to custom fields from $bean
$bean->custom_fields->retrieve();
// Get access to name property using DBManager because $bean->name return null
$sql = "SELECT name FROM accounts WHERE id = '{$bean->id}'";
$name = $GLOBALS['db']->getOne($sql);
// Assign a value to non-db field
$bean->name_c = empty($name) ? $bean->nombre_persona_c : $name;
}
}
I was not familiar with the method $bean->custom_fields->retrieve() and at the moment I do not know why is empty the name field and I understand others fields remain empty.
I hope this is useful
We achieved that doing an after_retrieve hook, very fast and simple - This is taken from a working example.
public function RemoveCost(&$bean, $event, $arguments)
{
global $current_user;
include_once(‘modules/ACLRoles/ACLRole.php’);
$roles = ACLRole::getUserRoleNames($current_user->id);
if(!array_search("CanSeeCostRoleName",$roles)){
$bean->cost = 0;
$bean->cost_usdollar = 0;
}
}
All you need is to define and add this function to the module logic_hooks.php
You can even tailor down to specific calls:
if (isset($_REQUEST['module'],$_REQUEST['action']) && $_REQUEST['module'] == 'Opportunities' && $_REQUEST['action'] == 'DetailView')
As some times there are views you do want to show the field, for example quicksearch popup.
I am trying to make a form which will allow them to update their entered unique entry. Suppose there is form which is used to collect, the User Specializations
And this Specializations field is gravity forms multiselect field which is dynamically set. And as they update their specializations also updated in entries tab.
So, i just want to allow they to have this multiselect field updation.
I came across a solution to add multiselect choice dynamically but that only populate the field with all the choices not the user selected also.
So, is there is way to set the user entered choices dynamically?
Possible Solution:
Like we can get the entries and then set search criterion to current user and will get a unique entry and then after we can set these selected values in the choices.
Issue Exists with the above possible solution:
but still there is issue like it will be creating new entry as form dont know it is update operation. So can anyone help?
//Auto Populate Service Field in Form ID=
add_filter('gform_pre_render_2', 'populate_services');
add_filter('gform_pre_validation_2', 'populate_services');
add_filter('gform_pre_submission_filter_2', 'populate_services');
add_filter('gform_admin_pre_render_2', 'populate_services');
function populate_services($form)
{
foreach ($form['fields'] as &$field) {
if ($field->type != 'multiselect' || strpos($field->cssClass, 'populate_services') === false) {
continue;
}
$services = get_specializations();
$choices = array();
foreach ($services as $service) {
$title = stripslashes($service->name);
$choices[] = array(
'value' => $service->ID,
'text' => esc_html($title)
);
}
// update 'Select Duration' to whatever you'd like the instructive option to be
$field->placeholder = 'Select Services';
$field->choices = $choices;
}
return $form;
}
Is there a way to create/update form poll fields based on a content type? For example, I've got a post type called Candidate and I'd like like to dynamically update a poll list when a new Candidate is added, or when one is removed.
The reason I'm looking for this is because I'm creating a voting mechanism for this client and they have requested that users see an image, the name, and brief Bio of who they are voting for. My idea is to tie in the names so that I can target a hidden Gravity Form poll on page so when the voter clicks, it updates the corresponding named checkbox.
I can of course add each Candidate one by one, and then add each candidate one by one in the form, but was hoping there was a way to do that in code. So far I haven't found much other than filters in the Gravity Forms Documentation.
To reiterate, my question here is not the frontend connection, rather how to dynamically update/add an option in a poll field in a form when content is created for a Candidate post type.
Any help would be appreciated.
I believe the solution you're after is documented here:
http://www.gravityhelp.com/documentation/gravity-forms/extending-gravity-forms/hooks/filters/gform_pre_render/
Probably a combination of solution examples #1 and #2 on that page will fit your needs? So -
Create a category of standard Wordpress pages (category name: "Candidates"), and the pages would contain the candidate information (bio, photo, etc).
In your functions.php file for your current theme, you'd add something like the following to pull out that category's worth of posts:
// modify form output for the public page
add_filter("gform_pre_render", "populate_checkbox");
// modify form in admin
add_filter("gform_admin_pre_render", "populate_checkbox");
function populate_dropdown($form) {
// some kind of logic / code to limit what form you're editing
if ($form["id"] != 1) { return $form; }
//Reading posts for "Business" category;
$posts = get_posts("category=" . get_cat_ID("Candidates"));
foreach ($form['fields'] as &$field) {
// assuming field #1, if this is a voting form that uses checkboxes
$target_field = 1;
if ($field['id'] != $target_field) { break; }
// init the counting var for how many checkboxes we'll be outputting
// there's some kind of error with checkboxes and multiples of 10?
$input_id = 1;
foreach ($posts as $post) {
//skipping index that are multiples of 10 (multiples of 10 create problems as the input IDs)
if($input_id % 10 == 0) { $input_id++; }
// here's where you format your field inputs as you need
$choices[] = array('text' => $post->post_title, 'value' => $post->post_title);
$inputs[] = array("label" => $post->post_title, "id" => "{$field_id}.{$input_id}");
// increment the number of checkboxes for ID handling
$input_id++;
}
$field['choices'] = $choices;
$field['inputs'] = $inputs;
}
// return the updated form
return $form;
}
Scenario
I am developing an internal CakePHP company application that has a despatch screen, which has three lists:
Available items for despatch (Shown below on the left - "Items Available for Packing")
Already packed items pulled from the database (Shown below on the right - "Packed Items")
Changes to the packed items list (Form submission after changes have been made)
The user can drag items from the left list to the right list and vice versa. Once the click the Save button, the form is submitted with the items on the right list.
Desired Result
As part of the save, I need to compare (using PHP) the updated list with the saved list from the database.
With any additions, I need to update the items record with the despatch ID.
With any removals, I need to update the items record to sell the despatch ID to NULL.
This would allow users to drag and drop items in both directions, then click Save and expect the page to load with the state they left the page in.
Current State
I am able to save items to be added to the list and, separately, save items being removed. However, I cannot get them working together. When I try this, one item being added to the list completely replace all the other items on the "Packed Items" list.
Code so far...
function edit() {
$this->Despatch->recursive = -1;
if (!empty($this->data)) {
if($this->Despatch->save($this->data)) {
/* NEED TO RETRIEVE CURRENT REPAIR IDs ASSOCIATED
WITH THE DESPATCH ID AND COMPARE WITH FORM SUBMISSION LIST TO
REMOVE THE DIFFERENCES */
# Retrieve current repair records where despatch_id = $this->id.
$this->Despatch->Repair->recursive = -1;
$current_associated_repairs = $this->Despatch->Repair->find('all', array(
'fields' => array('id', 'despatch_date', 'despatch_id'),
'conditions' => array('Repair.despatch_id =' => $this->data['Despatch']['id'])));
# Create array with repair IDs
$repairs = explode(",", $this->data['Repair']['ids']);
$i = 0;
foreach($repairs as $repair) {
$repairupdates[$i]['Repair']['id'] = $repair;
$i++;
}
# Delete array index to prevent it interfering with form saving later
unset($this->data['Repair']['ids']);
# 2. Find unmatched IDs between current records and form submission list of repairs
$length1 = sizeof($current_associated_repairs);
$length2 = sizeof($this->data['Repair']);
for ($i = 0; $i < $length1; $i++) {
for ($j = 0; $j < $length2; $j++) {
### LOGIC NOT CORRECT HERE !!! ###
### THIS WORKS FOR REMOVING PACKED INSTRUMENTS - FROM RIGHT TO LEFT ###
### BUT ACTUALLY BEING TRIGGERED WHEN ADDING FROM LEFT TO RIGHT TOO ###
if ($current_associated_repairs[$i]['Repair']['id'] == $this->data['Repair'][$j]['id']
&& !in_array($current_associated_repairs[$i]['Repair']['id'], $this->data['Repair'][$j])) {
# if it's in current repairs and not in form submission, set to null...
# otherwise, it must be an addition if there's no matches
# 3. Set the despatch_date and despatch_id fields of those records to NULL
$this->data['Repair'][$j+1]['id'] = $current_associated_repairs[$i]['Repair']['id'];
$this->data['Repair'][$j+1]['despatch_date'] = null;
$this->data['Repair'][$j+1]['despatch_id'] = null;
}
}
}
# 4. Save the new list of repairs to the current despatch
if($this->Despatch->save($this->data) && $this->Despatch->Repair->saveAll($this->data['Repair'])) {
$this->Session->setFlash(__('The despatch has been saved.', true), 'default', array('class' => 'success-scheme message'));
} else {
$this->Session->setFlash(__('The repair could not be updated with the despatch number. Please try again.', true), 'default', array('class' => 'error-scheme message'));
}
} else {
$this->Session->setFlash(__('The despatch could not be saved. Please try again.', true), 'default', array('class' => 'error-scheme message'));
}
$this->redirect($this->referer(array('action' => 'view', $this->data['Despatch']['id'])));
}
}
I think I've included all the detail anyone should need, but just ask if you need to know more. The main problem I'm having is understanding the logic the code for achieving this.
Many thanks in advance.
PS - JavaScript Code
// click handler for saving despatch - required to save sortable lists properly
$('#save_despatch').click(function(e) {
e.preventDefault();
// gives comma-separated array of instrument IDs, e.g. 12345, 56789...
var result = $('#sortable2').sortable('toArray');
$('#RepairIds').val(result);
$('form').submit();
});
I can not really figure out what you are doing now in your logic, but I will suggest an approach that should work without a doubt.
You have two lists, for simplicity: left and right. This code is sort of pseudocode because I do not fully understand what you need, but this way, the lists should remain updated, and it cant go wrong.
Logic before displaying the lists (in PHP):
//Retrieve records from mysql into two arrays->aLeft and aRight
//Create an MD5 hash to easily compare current en future lists.
$sCheckSum = md5(implode(",",$aLeft));
$_SESSION['checkSum'] = $sCheckSum;
//Generate your lists now
//Display output
JS:
$('#save_despatch').click(function(e) {
e.preventDefault();
// gives comma-separated array of instrument IDs, e.g. 12345, 56789...
var leftResult = $('#sortable2').sortable('toArray');
var rightResult = $('#sortableX').sortable('toArray'); //Make sure this matches your lists, as I have not seen your HTML
$('#Left').val(leftResult);
$('#Right').val(rightResult);
$('form').submit();
});
Then on the receiving end:
//Get the values of the #Left and #Right inputs in to $aLeft and $aRight
$sNewCheckSum = md5($aLeft);
if($sNewCheckSum != $_SESSION['checkSum'] ) //Left list is not the same, so the right is neither
{
foreach(explode(",",$aLeft) as $iRepairId){
//Not sure what should happen here, but thats up to you.
//Mysql update table SET ID = NULL WHERE repairdId = $iRepairId
}
foreach(explode(",",$aRight) as $iRepairId){
//Not sure what should happen here, but thats up to you.
//Mysql update table SET ID = xxx WHERE repairdId = $iRepairId
}
}