Search code examples
concatenationanypoint-studiomulesoft

Conditional concatenation in Data Weave


Is there a way to do conditional concatenation of a string. For instance, if the string has a value then add it, but if the string is null then don't. I am creating a long string that will become the body of an email message. The "payload.eachRecipient.company" field may have a value or may be null. I want to include the line in the email only if it has a value, but not display the "Company Name:" line if it doesn't.

payload.eachRecipient.city ++ ", " ++ payload.eachRecipient.state ++ " " ++ payload.eachRecipient.zipCode ++ "\n\n" ++
("Company Name: " ++ payload.eachRecipient.company (if payload.eachRecipient.company?)) ++ "\n" ++ "ID: " ++ payload.eachRecipient.sson ++ "\n" ++ "System Order Number: " ++ payload.eachRecipient.orderNum ++ "\n\n" ++
"Shipping Method: " ++ payload.eachRecipient.ShipVia ++ "\n\n" ++ "Order Summary:\n" ++ (vars.listOfMaterials.combinedString joinBy("\n")) ++

Solution

  • I wrote a function that takes the string that will be checked for a null value, anything you want to add to the front and anything you want to add to the back:

    fun checkNull(aString, aFront, aBack) = 
        if (aString == null)
            ""
        else
            aFront ++ aString ++ aBack
    

    The result of the function is concatenated into the longer string:

    (checkNull(payload.eachRecipient.company, "Company Name: ", "\n"))
    checkNull(payload.eachRecipient.line2, "", "\n\t")