Currently I have a select box that is filling in its data from the controller class. As of now all the values are filling in properly as intended, but there are some null values for firstname
for which I'm trying to add a ternary operator to replace it with email.
This doesn't seem to work in my controller class as I'm placing the parentheses wrong.
Here's my current code:
public function getContacts($id){
$option = "<option value='0'>Select</option>";
$modelList = $this->listings_model->get_contact(array('contact_type'=>3),'firstname,lastname,email,refno');
foreach($modelList as $m){
$option .= "<option value='".$m['firstname']." ".$m['lastname']." - ".$m['refno']."' id='".$m['id']."'>".$m['firstname']." ".$m['lastname']." - ".$m['refno']."</option>";
}
echo json_encode($option);
}
I've tried the following but I'm getting a syntax error:
$option .= "<option value='"($m['firstname'].$m['lastname'] ? $m['firstname']." ".$m['lastname']." - ".$m['refno'] : $m['email'])"' id='".$m['id']."'>".$m['firstname']." ".$m['lastname']." - ".$m['refno']."</option>";
What I want to achieve is this:
value="<?php echo ($ow['firstname'].$ow['lastname']?$ow['firstname'].' '.$ow['lastname']:($ow['email']?$ow['email']:$ow['mobile'])).' - '.$ow['refno']; ?>"
CodePudding user response:
We have these things called variable that help code become readable. Also, parentheses can help identify groups of variables with operations between them in a ternary operator. You have several misplaced '
and "
in your code, both in PHP and in HTML.
From what I understand from your requirements the following code does this:
if firstname and lastname are not empty it will use <firstname> <lastname> - <ref>
for the value and text of the option else it will use <email>
if email is not empty else <mobile>
$name = ( $m['firstname'] && $m['lastname'] ) ? ( $m['firstname'] . ' ' . $m['lastname'] ) : ( '' );
$value = $name ? ($name . ' - ' . $m['refno']) : ($m['email'] ? $m['email'] : $m['mobile']);
$id = $m['id'];
$option .= "<option value=\"$value\" id=\"$id\">$value</option>";
By the way, you cannot json_encode an HTML string.
CodePudding user response:
$m['firstname'].$m['lastname']
is the evil. You should be checking for null
value for only $m['firstname']
instead of the both.
Also, it should be:
$option .= "<option value='".($m['firstname'] !== null ? $m['firstname']." ".$m['lastname']." - ".$m['refno'] : $m['email'])."' id='".$m['id']."'>".($m['firstname'] !== null ? $m['firstname']." ".$m['lastname']." - ".$m['refno'] : $m['email'])."</option>";