tags:

views:

23

answers:

2

I have the following code:

$theinput = new inputSmartSearch($db,
    "chooseproduct", "Choose Product", $therecord["product"],
    "Choose Product", TRUE, NULL, NULL, TRUE, $required=true);
$theinput->setAttribute("class","important");
if(isset($therecord["product"]) || isset($therecord["cost"])) {
    $theinput->setAttribute("value",
        $therecord["product"] . ", " . $therecord["cost"]);
}

inputSmartSearch is a type of form field for a CMS system I am using.

What I am wanting to do to set the value of the form by default, as long as it is not empty, to avoid having the ", " be the default value.

var_dump($therecord["product"]); 

shows string(0) "", so it is certainly empty.

Why then is ", " still being set as the default value of my form field?

A: 

You want:

$myValue = ($therecord["product"]) ? $therecord["product"] . ", " . $therecord["cost"] : '';
$theinput->setAttribute("value",$myValue );

This will check if $therecord["product"] is empty and if it is, then make $myValue = '';

Yours would always print ", "; as there was nothing telling it not to.

You could also want one of the following:

if(isset($therecord["product"]) || isset($therecord["cost"])) {
    $myValue = '';
    if(!(empty($therecord["product"])) $myValue .= $therecord["product"].', ';
    if(!(empty($therecord["cost"])) $myValue .= $therecord["sot"];
    else $myValue = substr($myValue, 0, -2);
    $theinput->setAttribute("value", $myValue);
}

UPDATE

You have:

if(isset($therecord["product"]) || isset($therecord["cost"])) {
    $theinput->setAttribute("value",
        $therecord["product"] . ", " . $therecord["cost"]);
}

This says to me that if the variable $therecord["product"] or $therecord["cost"] exsits (even if empty) then set the value to be $therecord["product"], $therecord["cost"] so it could end up having any of the following outputs:

1) myprod, mycost
2) myprod,
3) , mycost
4) , 
Lizard
What am I doing wrong above? Also won´t your solution set $myValue to $therecord["product"] if it isn´t empty, which isn´t what I want?
Jacob
isset will check to see if var exists, what you may need is `empty` They will check if there is a value. _ I have updated my answer with another possible solution
Lizard
I have updated again, with the explantion of your code at the bottom
Lizard
+1  A: 

isset() checks if the variable is set and is not NULL, you need to check if it is empty. replace isset() with !empty() like this:

if (
    !empty($therecord["product"])||
    !empty($therecord["cost"])
) {
    $parts = array();
    if (!empty($therecord["product"])) {
        $parts[] = $therecord["product"];
    }
    if (!empty($therecord["cost"])) {
        $parts[] = $therecord["cost"];
    }
    $theinput->setAttribute("value", implode(', ', $parts));
}

EDIT: now puts comma only if needed

kgb