empty form text filed - forms

I'm using a FormTextField in a Flutter app
To update a certain column value, the user types in the FormTextField, otherwise leaves the field empty.
I tried this code, but it was adding a null value to the column, deleting the existing value. I'm not happy with this behavior.
String _getProd5Name() {
if ((_prod5Controller.text).isNotEmpty == true) {
_prod5String = _prod5Controller.text;
}
return _prod5String;
}
Is there a way to do it?
I found similar questions, but they are relevant to other languages and their solutions don't solve my case.

String _getProd5Name() {
// Actually you don't have to make it private
// since this is a local variable inside a function
String _prod5String = variableContainingInitialValue;
if (_prod5Controller.text.isNotEmpty) {
_prod5String = _prod5Controller.text;
}
return _prod5String;
}

Here is my advice, since I love wrapping everything on 1 line. You can change the "" part with your result expectation. It's the same with your logic but it's shorter and instead of returning null I make it returning the empty string "". And also (_prod5Controller.text).isNotEmpty == true you can just shorten it to (_prod5Controller.text).isNotEmpty because .isNotEmpty always returning boolean true/false and if-else consuming boolean
String _getProd5Name() {
return ((_prod5Controller.text).isNotEmpty) ? _prod5String = _prod5Controller.text : "";
}

Related

Salesforce trigger-Not able to understand

Below is the code written by my collegue who doesnt work in the firm anymore. I am inserting records in object with data loader and I can see success message but I do not see any records in my object. I am not able to understand what below trigger is doing.Please someone help me understand as I am new to salesforce.
trigger DataLoggingTrigger on QMBDataLogging__c (after insert) {
Map<string,Schema.RecordTypeInfo> recordTypeInfo = Schema.SObjectType.QMB_Initial_Letter__c.getRecordTypeInfosByName();
List<QMBDataLogging__c> logList = (List<QMBDataLogging__c>)Trigger.new;
List<Sobject> sobjList = (List<Sobject>)Type.forName('List<'+'QMB_Initial_Letter__c'+'>').newInstance();
Map<string, QMBLetteTypeToVfPage__c> QMBLetteTypeToVfPage = QMBLetteTypeToVfPage__c.getAll();
Map<String,QMBLetteTypeToVfPage__c> mapofLetterTypeRec = new Map<String,QMBLetteTypeToVfPage__c>();
set<Id>processdIds = new set<Id>();
for(string key : QMBLetteTypeToVfPage.keyset())
{
if(!mapofLetterTypeRec.containsKey(key)) mapofLetterTypeRec.put(QMBLetteTypeToVfPage.get(Key).Letter_Type__c, QMBLetteTypeToVfPage.get(Key));
}
for(QMBDataLogging__c log : logList)
{
Sobject logRecord = (sobject)log;
Sobject QMBLetterRecord = new QMB_Initial_Letter__c();
if(mapofLetterTypeRec.containskey(log.Field1__c))
{
string recordTypeId = recordTypeInfo.get(mapofLetterTypeRec.get(log.Field1__c).RecordType__c).isAvailable() ? recordTypeInfo.get(mapofLetterTypeRec.get(log.Field1__c).RecordType__c).getRecordTypeId() : recordTypeInfo.get('Master').getRecordTypeId();
string fieldApiNames = mapofLetterTypeRec.containskey(log.Field1__c) ? mapofLetterTypeRec.get(log.Field1__c).FieldAPINames__c : '';
//QMBLetterRecord.put('Letter_Type__c',log.Name);
QMBLetterRecord.put('RecordTypeId',tgh);
processdIds.add(log.Id);
if(string.isNotBlank(fieldApiNames) && fieldApiNames.contains(','))
{
Integer i = 1;
for(string fieldApiName : fieldApiNames.split(','))
{
string logFieldApiName = 'Field'+i+'__c';
fieldApiName = fieldApiName.trim();
system.debug('fieldApiName=='+fieldApiName);
Schema.DisplayType fielddataType = getFieldType('QMB_Initial_Letter__c',fieldApiName);
if(fielddataType == Schema.DisplayType.Date)
{
Date dateValue = Date.parse(string.valueof(logRecord.get(logFieldApiName)));
QMBLetterRecord.put(fieldApiName,dateValue);
}
else if(fielddataType == Schema.DisplayType.DOUBLE)
{
string value = (string)logRecord.get(logFieldApiName);
Double dec = Double.valueOf(value.replace(',',''));
QMBLetterRecord.put(fieldApiName,dec);
}
else if(fielddataType == Schema.DisplayType.CURRENCY)
{
Decimal decimalValue = Decimal.valueOf((string)logRecord.get(logFieldApiName));
QMBLetterRecord.put(fieldApiName,decimalValue);
}
else if(fielddataType == Schema.DisplayType.INTEGER)
{
string value = (string)logRecord.get(logFieldApiName);
Integer integerValue = Integer.valueOf(value.replace(',',''));
QMBLetterRecord.put(fieldApiName,integerValue);
}
else if(fielddataType == Schema.DisplayType.DATETIME)
{
DateTime dateTimeValue = DateTime.valueOf(logRecord.get(logFieldApiName));
QMBLetterRecord.put(fieldApiName,dateTimeValue);
}
else
{
QMBLetterRecord.put(fieldApiName,logRecord.get(logFieldApiName));
}
i++;
}
}
}
sobjList.add(QMBLetterRecord);
}
if(!sobjList.isEmpty())
{
insert sobjList;
if(!processdIds.isEmpty()) DeleteDoAsLoggingRecords.deleteTheProcessRecords(processdIds);
}
Public static Schema.DisplayType getFieldType(string objectName,string fieldName)
{
SObjectType r = ((SObject)(Type.forName('Schema.'+objectName).newInstance())).getSObjectType();
DescribeSObjectResult d = r.getDescribe();
return(d.fields.getMap().get(fieldName).getDescribe().getType());
}
}
You might be looking in the wrong place. Check if there's an unit test written for this thing (there should be one, especially if it's deployed to production), it should help you understand how it's supposed to be used.
You're inserting records of QMBDataLogging__c but then it seems they're immediately deleted in DeleteDoAsLoggingRecords.deleteTheProcessRecords(processdIds). Whether whatever this thing was supposed to do succeeds or not.
This seems to be some poor man's CSV parser or generic "upload anything"... that takes data stored in QMBDataLogging__c and creates QMB_Initial_Letter__c out of it.
QMBLetteTypeToVfPage__c.getAll() suggests you could go to Setup -> Custom Settings, try to find this thing and examine. Maybe it has some values in production but in your sandbox it's empty and that's why essentially nothing works? Or maybe some values that are there are outdated?
There's some comparison if what you upload into Field1__c can be matched to what's in that custom setting. I guess you load some kind of subtype of your QMB_Initial_Letter__c in there. Record Type name and list of fields to read from your log record is also fetched from custom setting based on that match.
Then this thing takes what you pasted, looks at the list of fields in from the custom setting and parses it.
Let's say the custom setting contains something like
Name = XYZ, FieldAPINames__c = 'Name,SomePicklist__c,SomeDate__c,IsActive__c'
This thing will look at first record you inserted, let's say you have the CSV like that
Field1__c,Field2__c,Field3__c,Field4__c
XYZ,Closed,2022-09-15,true
This thing will try to parse and map it so eventually you create record that a "normal" apex code would express as
new QMB_Initial_Letter__c(
Name = 'XYZ',
SomePicklist__c = 'Closed',
SomeDate__c = Date.parse('2022-09-15'),
IsActive__c = true
);
It's pretty fragile, as you probably already know. And because parsing CSV is an art - I expect it to absolutely crash and burn when text with commas in it shows up (some text,"text, with commas in it, should be quoted",more text).
In theory admin can change mapping in setup - but then they'd need to add new field anyway to the loaded file. Overcomplicated. I guess somebody did it to solve issue with Record Type Ids - but there are better ways to achieve that and still have normal CSV file with normal columns and strong type matching, not just chucking everything in as strings.
In theory this lets you have "jagged" csv files (row 1 having 5 fields, row 2 having different record type and 17 fields? no problem)
Your call whether it's salvageable or you'd rather ditch it and try normal loading of QMB_Initial_Letter__c records. (get back to your business people and ask for requirements?) If you do have variable number of columns at source - you'd need to standardise it or group the data so only 1 "type" of records (well, whatever's in that "Field1__c") goes into each file.

Set a different variable depending on bool expression in Dart

In Dart we might want to set a variable to some fixed value, but which variable we set may depend on some bool expression. For example
String value = 'Hello World!';
bool sendToFirst = false;
String first = '';
String second = '';
if (sendToFirst){
first = value;
else {
second = value;
}
This block would do what you want, but is there a more concise way of doing this? Something like
(sendToFirst ? first : second) = value;
But of course this does not work.
There is a way to simplify if statements: Ternary expressions.
Following your example you have to code:
sendToFirst ? first = value : second = value
In the end you are just replacing the keywords with syntactic sugar, where the ? replaces the "if bool is true"-part, followed by a condition that should be executed (the body of the condition) and the colon : for the else-part, again, followed by a body.
FYI: You can mark value final, if you are not planning to re-asign a new value to it.

I have a query that returns '[ ]'. I want it to be shown on a widget as not having any value, how do I do this?

I have a query in my flutter app that should return empty if 'archived' 'isNull' is set to true. I accomplished that, but the issue I'm having now is the fact that the query returns empty (i.e [ ]). And on the widget, I want this to be shown as not having any value but instead, an empty pair of brackets '()' keep showing up.
I have tried checking for when query data equals null, something like this:
if (queryResult.data == null){
// The idea is for it not to just return '()' as the value
value = null;
}
else{
value = queryResult.data;
}
And also:
if (queryResult.data == []){
value = null;
}
else{
value = queryResult.data;
}
How do I go about this? Thanks in advance.
If "data" is a list why not try data.isEmpty() ? And also if you only need to avoid the brackets (dirty fix alert ⚠️) whatever you did it's returning a string value '()' then you check that
if(yourResults == '()' )value == null;
And please add more details for a better answer .

Return empty strings in woocommerce checkout form

I'd like to return empty strings on all checkout form field but one (the billing_country one).
I already know how to do it with all fields :
add_filter('woocommerce_checkout_get_value','__return_empty_string', 1, 1);
And how to do it with only one field:
add_filter('woocommerce_checkout_get_value','custom_checkout_get_value_ship_ville', 10, 2);
function custom_checkout_get_value_ship_ville( $value, $imput ){
if($imput == 'shipping_city')
$value = '';
return $value;
}
But for all but one ... I'm a little stucked.
I succeed by duplicating and adapting the previous function, but it's a lot of code for just returning empty strings.
I tried with else, elsif, switch and with logical operators, but no result.
So if someone have some clue ...
Thanks
If you want to return empty strings on every value of $imput except for one specific value you need to reverse the comparison of your second code snippet. So instead of comparing wether the $imput is equal to a value you compare wether the $imput is NOT equal to a value.
You can read up on this comparison here: http://php.net/manual/en/language.operators.comparison.php
You can also just return an empty string directly without assigning it to a variable:
add_filter('woocommerce_checkout_get_value','custom_checkout_get_value_ship_ville', 10, 2);
function custom_checkout_get_value_ship_ville( $value, $imput ){
if($imput != 'billing_country') {
return '';
}
}

How do I perform an action on a field for Swift UI Tests based on the contents/state of the field?

I have a usernameField. On initial state, the field is empty. If I log in successfully, and log back out, it remembers my username for me.
Trying to create a test case for iOS (in swift) that will clear out the field (use the clearText button) if the field has content and then enter a desired string. If it's empty, it needs to skip the clearText button action (since it doesn't exist when the field value is nil) and go straight to entering the username.
It always skips the if statement, even when it's true. Looks for the clearText button, and fails. Works if there's a value in the field, though.
Tried lots of different approaches, but here's my best current working code. Open to any suggestions, as I have no one to really help me learn this stuff. I'm sure I'm just missing something fundamental:
let staffusernameloginfield = app.scrollViews.otherElements.textFields["staffUsernameLoginField"]
staffusernameloginfield.tap()
func checkUsernameFieldContents() {
if staffusernameloginfield == (Content:nil) {
staffusernameloginfield.typeText("owner")
}
else {
elementsQuery.buttons["Clear text"].tap()
staffusernameloginfield.typeText("owner")
}
}
checkUsernameFieldContents()
Have also tried:
if staffusernameloginfield == ("") {
staffusernameloginfield.typeText("owner")
}
else {
elementsQuery.buttons["Clear text"].tap()
staffusernameloginfield.typeText("owner")
}
}
I know that I could hack it by having it always enter a value into the field and then clear it out and enter the desired value, but in this test case, I'm not trying to test for that.
I would compare the value (raw attribute of the element). This type can vary so I always do it as a string:
if staffusernameloginfield.value as! String == "" {
staffusernameloginfield.typeText("owner")
}
else {
elementsQuery.buttons["Clear text"].tap()
staffusernameloginfield.typeText("owner")
}
Now it should enter 'owner' if it sees there is no value in staffusernameloginfield.
to check if the textfield is empty:
app.textFields["signInEmailAddressTextFieldLabel"].value as? String == ""
if the textfield is empty, then that's true
I usually use an assert to check if the value is empty or not, in this example the value is equal to a variable incorrectPassword:
XCTAssertEqual(app.textFields["\(passwordSecureTextFieldLabel)"].value as? String, incorrectPassword)