This is a 2 part question about what approach is best. In this context all my code is in Controllers.
Part 1
Firstly, I just read that in a controller one should never used echo, is that true?
For instance, I had
public function actionCreate()
{
$model = new ClientsContacts();
if ($model->load(Yii::$app->request->post())) {
$model->dtCreation = date('Y-m-d H:i:s');
if ($model->validate()) {
$model->save();
echo json_encode(['status' => 'Success', 'message' => '<span class="glyphicon glyphicon-ok"></span> New entry created successfully.']);
}else{
echo json_encode(['status' => 'Error', 'message' => '<span class="glyphicon glyphicon-remove"></span> Model not valid!']);
}
} else {
return $this->renderAjax('create', [
'model' => $model,
]);
}
}
and it should be
public function actionCreate()
{
$model = new ClientsContacts();
if ($model->load(Yii::$app->request->post())) {
$model->dtCreation = date('Y-m-d H:i:s');
if ($model->validate()) {
$model->save();
return json_encode(['status' => 'Success', 'message' => '<span class="glyphicon glyphicon-ok"></span> New entry created successfully.']);
}else{
return json_encode(['status' => 'Error', 'message' => '<span class="glyphicon glyphicon-remove"></span> Model not valid!']);
}
} else {
return $this->renderAjax('create', [
'model' => $model,
]);
}
}
Part 2
I use certain actionGet… with Ajax to update Selects. The code that I found originally was
public function actionGetContactInfo($id){
$countContacts = ClientsContacts::find()
->where(['ContactId' => $id])
->count();
if( $countContacts > 0 ){
$Contact = ClientsContacts::findOne($id);
return $Contact->ContactInfo;
}
}
is there any reason I can’t simply use:
public function actionGetContactInfo($id){
$output = '';
$contact = ClientsContacts::findOne($id);
if( $contact ){
$output .= $contact ->ContactInfo;
}
return $output;
}
Just seem odd to use to call, one for a counter and then another to get the actual data.
This is all very new to me, so if you are inclined, please explain so I can learn.
I truly appreciate your insight into these issues!