Conditional Required Field - javascript

I have two fields in my module called: rules_name_c which is a text field and rules_author_c which is a relate field.
These fields are not mandatory fields however when i enter data into the rules_name_c field I would like to make it so the rules_author_c must be filled in to complete the record.
I have tried the following:
<?php
$dependencies['conn_connection']['required_author'] = array(
'hooks' => array("edit"),
'trigger' => 'true', //Optional, the trigger for the dependency. Defaults to 'true'.
'triggerFields' => array('rules_name_c'),
'onload' => true,
//Actions is a list of actions to fire when the trigger is true
'actions' => array(
array(
'name' => 'SetRequired',
//The parameters passed in will depend on the action type set in 'name'
'params' => array(
'target' => 'rules_author_c',
'label' => 'rules_author_c_label',
'value' => 'not(equal($rules_name_c, ""))',
),
),
),
);
?>
I believe this solution will not work as this only functions when editing a record. Is that correct?
I have also tried using:
<?php
require_once('include/MVC/View/views/view.edit.php');
/*
* replace UT_Blogs with the module your are dealing with
*/
class conn_connectionViewEdit extends ViewEdit {
public function __construct() {
parent::ViewEdit();
$this->useForSubpanel = true; // this variable specifies that these changes should work for subpanel
$this->useModuleQuickCreateTemplate = true; // quick create template too
}
function display() {
global $mod_strings;
//JS to make field mendatory
$jsscript = <<<EOQ
<script>
// Change rules_author_c to the field of your module
$('#rules_name_c').change(function() {
makerequired(); // onchange call function to mark the field required
});
function makerequired()
{
var status = $('#rules_name_c').val(); // get current value of the field
if(status != ''){ // check if it matches the condition: if true,
addToValidate('EditView','rules_author_c','varchar',true,'{$mod_strings['LBL_RULES_AUTHOR']}'); // mark rules_author_c field required
$('#description_label').html('{$mod_strings['LBL_RULES_AUTHOR']}: <font color="red">*</font>'); // with red * sign next to label
}
else{
removeFromValidate('EditView','rules_author_c'); // else remove the validtion applied
$('#rules_author_c_label').html('{$mod_strings['LBL_RULES_AUTHOR']}: '); // and give the normal label back
}
}
makerequired(); //Call at onload while editing a Published blog record
</script>
EOQ;
parent::display();
echo $jsscript; //echo the script
}
}

I wrote this javascript function and later on I use it with jQuery:
function lxValidateCRMfield(form_name, field_name, label, validate, fnCallerName = "") {
fnCallerName = (fnCallerName != "") ? "(Function " + fnCallerName + ")" : "";
if (validate) {
console.log("lxValidateCRMfield adding validation on form " + form_name + " to field " + field_name, fnCallerName);
//addToValidate is defined somewhere on suitecrm
addToValidate(form_name, field_name, 'varchar', true, "Falta campo requerido: " + label);
$('#' + field_name + '_label').html(label + ': <font color="red">*</font>');
} else {
console.log("lxValidateCRMfield removing validation on form " + form_name + " to field " + field_name, fnCallerName);
//removeFromValidate is defined somewhere on suitecrm
removeFromValidate(form_name, field_name);
$('#' + field_name + '_label').html(label + ': ');
}
}
Then you call it on the form you need to (using your fields it could look like this):
// List all forms available
console.log(document.forms);
// select one you need
var form_name = 'EditView'; eg: EditView, DetailView, search_form
var module = 'YourModule'; // eg: Opportunities
var crmEditView = document.forms[form_name];
if (crmEditView.module.value == module) {
if ($('#rules_name_c').val() != '') {
lxValidateCRMfield(form_name, 'rules_author_c', 'Author', true, 'optionalNameOfFunctionYourCallingThis');
} else {
lxValidateCRMfield(form_name, 'rules_author_c', 'Author', false, 'optionalNameOfFunctionYourCallingThis');
}
}
I hope it helps
Regards

Related

Woocommerce: How to show Product Attribute name and Category name on title

Using the answer provided in this thread (Woocommerce: How to show Product Attribute name on title when in a category page and "filtering" products via '?pa_attribute=' on address bar) I would like to display the category as well as the attribute name. I have a separate JS function that is currently updating the page_title when a filter is applied but that is only loading after ajax has finished. So in this event it would not load till after the filter is applied.
In the event that a user uses the nav to get to the category, currently only the attribute is displaying in the page_title. Looking to also display the category. I believe this would work out of the box if I organized my products in to subcategories but due to how the filtering is being set up I elected not to go this route. I can explain in further detail why I had to take this approach if anyone is interested.
I have left the commented out code in so that you can see the approach I was attempting to take. If this is confusing can edit it out.
add_filter( 'woocommerce_page_title', 'custom_woocommerce_page_title', 15, 2 );
function custom_woocommerce_page_title( $page_title ) {
if ( is_archive() ) {
$exists_attr = false;
foreach ( $_GET as $index => $value ) {
if ( substr( $index, 0, 3 ) === 'pa_' ) {
//$cat_id = wc_category_taxonomy_id_by_name( $index );
$attr_id = wc_attribute_taxonomy_id_by_name( $index );
if ( $attr_id === 0 && $cat_id ) {
continue;
}
if ( ! $exists_attr /* && ! $exists_cat */) {
$exists_attr = true;
//$exists_cat = true;
$page_title .= ' ';
} else {
$page_title .= ' ';
}
//$terms = get_the_terms( $post->ID, 'product_cat' );
$term = get_term_by( 'slug', esc_html( $value ), $index );
$page_title = /*$terms->name . ': ' . */ $term->name;
}
}
}
// Need to add category name after attribute term name.
return $page_title;
}
Also, I have included the JS I am using to apply page_title in the event a filter selection occurs. Ideally it would be great if I could handle it all via a JS file as I am much more familiar with JS and just starting to dive in to php. I am using the WOOF - WooCommerce Products Filter and modifying some of the code to accomplish what I need.
(function() {
var machineEl = document.getElementsByClassName('woof_select woof_select_pa_machine')[0];
var processEl = document.getElementsByClassName('woof_select woof_select_pa_processing')[0];
var optionMachine = machineEl.querySelector("option[selected='selected']");
var optionProcess = processEl.querySelector("option[selected='selected']");
var machineValue = optionMachine.innerHTML;
var processValue = optionProcess.innerHTML;
var result = document.getElementsByClassName('woocommerce-products-header__title page-title')[0];
if (machineValue != 'Product Machine' && processValue != 'Product Processing') {
result.innerHTML = machineValue + " " + processValue;
}
else if (machineValue != 'Product Machine') {
result.innerHTML = machineValue;
}
else if (processValue != 'Product Processing') {
result.innerHTML = processValue;
}
})()
So was able to get this to work by taking my JS and adding it in as a script within my functions.php. So essentially I was able to eliminate the custom_woocommerce_page_title filter.
Function.php
<?php
add_action('wp_footer', 'onLoadPageTitle');
function onLoadPageTitle() {
?>
<script>
machineEl = document.getElementsByClassName('woof_select woof_select_pa_machine')[0];
processEl = document.getElementsByClassName('woof_select woof_select_pa_processing')[0];
optionMachine = machineEl.querySelector("option[selected='selected']");
optionProcess = processEl.querySelector("option[selected='selected']");
if (optionMachine != null) {
machineValue = optionMachine.innerHTML;
}
else {
machineValue = "";
}
if (optionProcess != null) {
processValue = optionProcess.innerHTML;
}
else {
processValue = "";
}
result = document.getElementsByClassName('woocommerce-products-header__title page-title')[0];
result.innerHTML = machineValue + " " + processValue;
</script>
<?php
}
?>
Then the woof woocommerce filter js that updates the title when a new select occurs after the AJAX.
(function() {
machineEl = document.getElementsByClassName('woof_select woof_select_pa_machine')[0];
processEl = document.getElementsByClassName('woof_select woof_select_pa_processing')[0];
optionMachine = machineEl.querySelector("option[selected='selected']");
optionProcess = processEl.querySelector("option[selected='selected']");
if (optionMachine != null) {
machineValue = optionMachine.innerHTML;
}
else {
machineValue = "";
}
if (optionProcess != null) {
processValue = optionProcess.innerHTML;
}
else {
processValue = "";
}
result = document.getElementsByClassName('woocommerce-products-header__title page-title')[0];
result.innerHTML = machineValue + " " + processValue;
})()
will probably pare it down by just calling the script function from within the woof js after ajax.

Reg Ex doesnt validate if i use # along with other characters or number

this is the same question i asked before. sorry but i check all the link provided it doesnt help. and sorry this is the first time i asked question here so was not very clear about how to ask
I am explaining here again with full details:
i have an input text field.
I Use jquery to validate the input date entered by user in this input box.
I pass the data enter as parameter in javascript GET method and pass it to PHP and validate it there with simple REG Ex. It does validate in all account. But if i add # with any test case this validation fails.
my code:
Input field:
<div id="clntFstName" >
<label for="clnt_fst_name">First Name</label>
<input type="text" id="clnt_fst_name" name="clnt_fst_name" onBlur="checkFieldValid(this.value, this);" value=""/>
<div class="msgError"></div>
</div>
If you the function CheckFieldValid is called as the user leaves a field input box.
java script:
function checkFieldValid(value, obj) {
var elem = obj.name;
$('#' + elem).parent().children('.msgError').html('');
var $label = $("label[for='" + obj.id + "']").text();
var $id = obj.id;
$.getJSON("ajax/registerClient.php?action=checkInputFieldValid&varField=" + value + "&lab=" + $label + "&id=" + $id, function(json) {
if (json.status.length > 0) {
$.each(json.status, function() {
if (this['fail'] == 'fail') {
var info = '<div class="warningMsg"> ' + this['message'] + '</div>';
$('#' + elem).parent().children('.msgError').html(info);
$('#' + elem).focus();
$('#' + elem).val("");
}
if (this['success'] == 'success') {
$('#' + elem).parent().children('.msgError').html('this is success');
}
});
if (json.status == 'empty') {
$('#' + elem).parent().children('.msgError').html('this is empty');
}
}
});
}
PHP code:
if($_GET['action'] == 'checkInputFieldValid'){
if(!empty($_GET['varField'])){
// this creates dynamic session variables and add values to it.
$_SESSION[$_GET['id']] = $_GET['varField'];
if(preg_match('/^[a-zA-Z]+$/',$_GET['varField'])){
$txtVar = 'It is a valid '.$_GET['lab'];
array_push($validFieldArray, array('success' => 'success', 'message' => $txtVar));
echo json_encode(array('status' => $validFieldArray));
$errorJScript = 0;
}else{
$txtVar = 'Enter a valid '.$_GET['lab'];
array_push($validFieldArray, array('fail' => 'fail', 'message' => $txtVar));
unset($_SESSION[$_GET['id']]);// unset the session variable to clear when page refresh
echo json_encode(array('status' => $validFieldArray));
$errorJScript = 1;
}
}
}
I dont know where I am wrong? I did all as told by other members May be I am doing something wrong with Java script when I pass the GET request variables? as far as
I think I did exactly what other member told me about PHP part. but may be the data is wrong when i take it from Java script part? As i checked it with other values return from PHP. but when I put # in my input box IT does not make the AJAX call and doesnt return the JSON nor set the session variable. So probably when I pass the varible as GET parameter It doesnt run the AJAX and just doesnt validate so plz tell me how can i pass # as GET parameter so that i correctly validate the fields in my PHP .
Plz help I will loos my job :(
Your $.getJSON call should use encodeURIComponent() to make sure you're not creating the wrong URL:
$.getJSON("ajax/registerClient.php?action=checkInputFieldValid&varField=" +
encodeURIComponent(value) +
"&lab=" +
encodeURIComponent($label) +
"&id=" +
encodeURIComponent($id), function(json) {
If you don't do that, then a # character will be interpreted as signalling the start of the hash field of the URL, and the rest of the URL will be ignored.

Cannot read property 'setCustomValidity' of null?

I have this script:
(function (exports) {
function valOrFunction(val, ctx, args) {
if (typeof val == "function") {
return val.apply(ctx, args);
} else {
return val;
}
}
function InvalidInputHelper(input, options) {
input.setCustomValidity(valOrFunction(options.defaultText, window, [input]));
function changeOrInput() {
if (input.value == "") {
input.setCustomValidity(valOrFunction(options.emptyText, window, [input]));
} else {
input.setCustomValidity("");
}
}
function invalid() {
if (input.value == "") {
input.setCustomValidity(valOrFunction(options.emptyText, window, [input]));
} else {
console.log("INVALID!"); input.setCustomValidity(valOrFunction(options.invalidText, window, [input]));
}
}
input.addEventListener("change", changeOrInput);
input.addEventListener("input", changeOrInput);
input.addEventListener("invalid", invalid);
}
exports.InvalidInputHelper = InvalidInputHelper;
})(window);
InvalidInputHelper(document.getElementById("firstname"), {
defaultText: "Please enter an firstname !",
emptyText: "Please enter an firstname!",
invalidText: function (input) {
return 'The firstnames "' + input.value + '" is invalid!';
}
});
and i have this textbox:
#Html.TextBoxFor(m => m.Register.FirstName, new { id = "firstname", #class = "form-control", #required = "required" })
But i get an error Cannot read property 'setCustomValidity' of null in console...what am i doing wrong? I see that is working here http://jsfiddle.net/B4hYG/437/ but for me its not...is it beacause of mvc or what?
That script, where in your code is it located? I'm guessing it's located in the header?
In your example, if you change the second drop-down at the top left to No wrap - in <head>, you get the error you described and you can see it being broken here.
This is because your elements haven't been created yet. Either you need to move your InvalidInputHelper function call to the bottom of the page so it runs after the elements are created, or you need to wrap it in a function to tell it to not fire until everything has run.
If you are definitely using jQuery you can wrap it with the ready function like so:
$('document').ready(function(){
InvalidInputHelper(document.getElementById("firstname"), {
defaultText: "Please enter an firstname !",
emptyText: "Please enter an firstname!",
invalidText: function (input) {
return 'The firstnames "' + input.value + '" is invalid!';
}
});
});
and here it is working.
Or if you prefer a pure JavaScript solution you can use the vanilla alternative found here.
To reiterate though, the easiest way would be to move the call to the bottom of the page, if you can.
i cannot "add a comment"... i reply here...
I think that the problem could be the 'document.getElementById("firstname")'.
You get it after the DOM is ready? (i don't know how MVC work)
Try to put your code:
InvalidInputHelper(document.getElementById("firstname"), {
defaultText: "Please enter an firstname !",
emptyText: "Please enter an firstname!",
invalidText: function (input) {
return 'The firstnames "' + input.value + '" is invalid!';
}
});
in document loaded function
(example for jquery:
$(function() { /* your code here */ }); )
In react you should use event.target.setCustomValidity

Inner Joined Tables with Search Engine in Javascript wont produce query to databse

I am having the search form query a inner joined table from multiple other tables in MySQL. I am using a local intranet with Xampp/Apache with When I run the SQL in PHPMyAdmin, it runs Perfect and produces the results exactly as I want them to appear on my website.
My database name is: loodt
My tables are: ee, er, aa, adjuster and attorney.
I have foreign keys on the ee table for the other tables (ee.er_id = er.id) etc...
However, when I try to run a search on my website, it pops up an error saying
"Could not query database for search results, MYSQL ERROR Table 'loodt.ee a" doesn't exist."
So I tried taking away the shortcut letters [referenced below in code] (A, B, C, D< E, & F) and typing in ee.name, er.name, etc... instead of assigning these letters and it didnt work either.
I was using the search engine already to query results from a single table before I started to modify it a few days ago, So I know it works and has to be an issue with the "temporary" table and my lack of knowledge of course.
Here is the search engine javascript:
$(function(){
//Hide the result list on load
$('#results-list').hide();
//Click event when search button is pressed
$('#search').click(function(){
doSearch();
});
//Keypress event to see if enter was pressed in text input
$('#text').keydown(function(e){
if(e.keyCode == 13){
doSearch();
}
});
});
>
function doSearch() {
var searchText = $('#text').val();
//Rehide the search results
$('#results-list').hide();
$.ajax({
url: './search.php',
type: 'POST',
data: {
'text': searchText
},
beforeSend: function(){
//Lets add a loading image
$('#results-holder').addClass('loading');
},
success: function(data) {
//Take the loading image away
$('#results-holder').removeClass('loading');
//Was everything successful, no errors in the PHP script
if (data.success) {
//Clear the results list
$('#results-list').empty();
//Display the results
//Check to see if there are any results to display
if(data.results.length > 0) {
//Loop through each result and add it to the list
$.each(data.results, function(){
//Give the list element a rel with the data results ID incase we want to act on this later, like selecting from the list
$('#results-list').append(
"<li rel='" + this.A_name + "'>" + this.D_name + " | " + this.A_file_no + " | " + this.A_claim_no + " | " + this.A_adj_no + " | " + this.F_acronym + " | " + this.A_doi + " | " + this.A_opened + " | " + this.A_status + " | " + this.A_redwells + " | " + this.E_firm_name + " | " + this.B_name + " | " + this.C_initials + " </li>");
});
} else {
//If there are no results, inform the user - add 'no-results' class so we can style it differently
$('#results-list').append("<li class='no-results'>Your search did not return any results</li>");
}
//Show the results list
$('#results-list').fadeIn();
} else {
//Display the error message
alert(data.error);
}
}
});
}
The javascript file above is called from my index page in the header, not sure if that is important. And this is the search.php file that is called inside the javascript code above.
> <?php
//Prepare an array to hold data we are going to send back to the jQuery
$data = array(
'results' => array(),
'success' => false,
'error' => ''
);
//Has the text been posted?
if (isset($_POST['text'])) {
//Connect to the database
>
$dbhost = 'localhost'; //hostname
$dbuser = 'xxxx'; //database username
$dbpass = 'xxxxx'; //database password
$dbname = 'loodt'; //database name
>
//Create the connection to the mySQL database or catch the exception if there is an error
$db = new mysqli($dbhost, $dbuser, $dbpass);
>
$db->select_db($dbname);
>
if($db->connect_errno > 0){
die('ERROR! - COULD NOT CONNECT TO mySQL DATABASE: ' . $db->connect_error);
}
>
> //Escape the text to prevent SQL injection
$text = $db->real_escape_string($_POST['text']);
//Run a LIKE query to search for titles that are like the entered text
>
$q = "SELECT `A.name AS A_name`, `D.name AS D_name`, `A.file_no AS A_file_no`, `A.claim_no AS A_claim_no`,
`A.adj_no AS A_adj_no`, `F.acronym AS F_acronym`, `A.doi AS A_doi`, `A.opened AS A_opened`,
`A.status AS A_status`, `A.redwells AS A_redwells`, `C.initials AS C_initials`, `B.name AS B_name`, `E.firm_name AS E_firm_name`
FROM `ee A`
INNER JOIN `adjuster B` ON `A.adjuster_id` = `B.id`
INNER JOIN `attorney C` ON `A.attorney_id` = `C.id`
INNER JOIN `er D` ON `A.er_id` = `D.id`
INNER JOIN `aa E` ON `A.aa_id` = `E.id`
INNER JOIN `wcab F` ON `A.wcab_id` = `F.id`
>
WHERE
`A_name` LIKE '%{$text}%' OR `A_file_no` LIKE '%{$text}%' OR `A_claim_no` LIKE '%{$text}%' OR `A_adj_no` LIKE '%{$text}%' OR `A_doi` LIKE '%{$text}%'";;
$result = $db->query($q);
//Did the query complete successfully?
if (!$result) {
//If not add an error to the data array
$data['error'] = "Could not query database for search results, MYSQL ERROR: " . $db->error;
} else {
//Loop through the results and add to the results array
while ($row = $result->fetch_assoc()) {
$data['results'][] = array(
'A_name' => $row['A_name'],
'D_Name' => $row['D_name'],
'A_file_no' => $row['A_file_no'],
'A_claim_no' => $row['A_claim_no'],
'A_adj_no' => $row['A_adj_no'],
'F_acronym' => $row['F_acronym'],
'A_doi' => $row['A_doi'],
'A_opened' => $row['A_opened'],
'A_status' => $row['A_status'],
'A_redwells' => $row['A_redwells'],
'C_initials' => $row['C_initials'],
'B_name' => $row['B_name'],
'E_firmname' => $row['E_firmname']
);
}
//Everything went to plan so set success to true
$data['success'] = true;
}
}
//Set the content type for a json object and ensure charset is UTF-8. NOt utf8 otherwise it will not work in IE (Darn IE! >.<)
header("Content-Type: application/json; charset=UTF-8");
//json encode the data and cast to an object so we can reference items like this.id in the javascript instead of this['id'] etc.
echo json_encode((object)$data);
?>
Here is link to the image of the SQl query and the column names:
enter link description here

How to change a javascript function's parameter from callback function

I have an HTML input element generated by the server and it looks like this:
HERE IS THE SERVER SIDE
"<input id='" + cRoadList.getRoadListNumber() + ",start_km' style='' type=\"text\" value='"+ cRoadList.getStartKm() + "' onkeypress='handleRoadListDataUpdate(\""+cRoadList.getStartKm()+"\")'
As you see the attrbutes of the input element are generated dynamically but that is not the case so let's simplify it by putting some static data like this:
"<input id='myID' style='' type=\"text\" value='100' onkeypress='handleRoadListDataUpdate(\"100\")'
The most important part of this HTML input element is the onkeypress event which calls the function handleRoadListDataUpdate
HERE IS THE CLIENT PART
function handleRoadListDataUpdate(oValue) // The function accpets the old value of the *input* element
{
var event = handleRoadListDataUpdate.caller.arguments[0] || window.event ;
var keyPressed = event.keyCode;
if(keyPressed == 13)
{
var roadListNumber = event.target.id.split(",")[0];
var inputId = event.target.id.split(",")[1];
var nValue = event.target.value;
if(nValue != oValue)
{
var userAction = confirm("Are you sure you want to change this value?\nPrevious value: " + oValue + "\nNew value: " + nValue);
if(userAction == true)
{
var url = "/GBS/RoadListController";
var params = "type=updateRoadList&roadListNumber=" + roadListNumber + "&updateData="+inputId + "&newValue="+ nValue;
dhtmlxAjax.post(url,params,function(loader)
{
var xmlDoc = loader.xmlDoc.responseXML;
var sqlResponse = xmlDoc.documentElement.getElementsByTagName("response");
var result = sqlResponse[0].getAttribute("value");
if(result == "sql_error")
{
alert("The operation could not be completed because of an network error!");
event.target.value = oValue;
}
else if(result == "sql_success")
{
alert("The operation completed successfully!");
//Change the parameter oValue of the parent function
}
});
}
else
{
event.target.value = oValue;
}
}
}
}
Basically this function is about updating (using ajax) the database with the new value the user enters inside the input element and press key Enter. If the parameter oValue is different than the parameter in the input element an ajax request is made so the database can be updated with the new value.
When the operation completes we have the new value in the input element (which is entered by the user) but the problem is that if he press Enter again the function get executed AGAIN because its parameter oValue is not changed with the new value.
So my very question is:
How to change the handleRoadListDataUpdate() function's parameter oValue to become the same as nValue so if the user press Enter by accident the function does not execute the ajax part again?
P.S.
Please no jQuery code! Only pure javaScript!

Categories

Resources