Yii Mailer PHP Error Array to string conversion
-
20-06-2021 - |
質問
The problem is the checkboxlist selection which is a multiple select. When I remove the following mailer code from the controller, the form is emailed... '{serviceItem}' => $model->selection,
In the model, the following explode and implode is used for putting the selection into the db table correctly...
public function afterFind()
{
$this->selection=explode(',',$this->selection);
return true;
}
/*implode your selection */
public function beforeSave()
{
$this->selection=implode(',',$this->selection);
return true;
}
If implode beforeSave...
[quote="php manual"] Returns a string containing a string representation of all the array elements in the same order, with the glue string between each element.[/quote]
And the mailer $message = strtr
returns a string from the array...
[quote="phpmanual"]strtr - If given two arguments, the second should be an array in the form array('from' => 'to', ...). The return value is a string where all the occurrences of the array keys have been replaced by the corresponding values...
$message = strtr ('Submitted on: {submissionDate}
Name: {firstName} {lastName}
Service Item: {serviceItem}
Visitor Comments: {message}', array(
'{submissionDate}' => $model->date,
'{firstName}' => $model->firstName,
'{lastName}' => $model->lastName,
'{serviceItem}' => $model->selection,
'{message}' => $model->comments));
Q. Why is there an error? and...
Q. What is the solution for the $model->selections to be sent in the email?
解決
Q. Why is there an error?
Answer:
First strtr()
expects the array to be of the form array('stringFROM'=>'stringTO')
and not array('stringFROM'=>array(...))
.
You are getting the second format(and hence the error) because $model->selection
is an array, since you have done an explode()
in afterFind()
.
afterFind()
is called whenever you load a model with any of the find
methods of CActiveRecord(i.e find()
, findAll()
, findByPk()
, findByAttributes()
, and so on), and if i am correct you are calling one of those of methods to get your current model.
Q. What is the solution for the $model->selections to be sent in the email?
Answer:
In this case you can simply do an implode()
again, to get a string:
'{serviceItem}' => implode(',',$model->selection);