Hi there,
I am new to Yii2 and trying to figure out how to implement a helper class which can be accessed global in order to format date and time using the Yii2 Advanced Template.
I have created a file with custom class in /application/frontend/components/
The class file is as follows:
namespace frontend\components\formatDate;
class formatDate {
const DATE_FORMAT = 'php:yyyymmdd';
const DATETIME_FORMAT = 'php:yyyymmddHis';
const TIME_FORMAT = 'php:His';
public static function convert($dateStr, $type='date', $format = null) {
if ($type === 'datetime') {
$fmt = ($format == null) ? self::DATETIME_FORMAT : $format;
}
elseif ($type === 'time') {
$fmt = ($format == null) ? self::TIME_FORMAT : $format;
}
else {
$fmt = ($format == null) ? self::DATE_FORMAT : $format;
}
return \Yii::$app->formatter->asDate($dateStr, $fmt);
}
}
I have added an extra line in frontend/web/index.php to use the new class file:
require(__DIR__ . '/../../vendor/autoload.php');
require(__DIR__ . '/../../vendor/yiisoft/yii2/Yii.php');
require(__DIR__ . '/../../common/config/bootstrap.php');
require(__DIR__ . '/../config/bootstrap.php');
require(__DIR__ . '/../components/formatDate.php');
I have the following action in a controller:
public function actionCreate()
{
$model = new Projects();
if ($model->load(Yii::$app->request->post())) {
$model->date_created = $model->dateAttr = formatDate::convert($model->dateAttr);
if ($model->save()) {
return $this->redirect(['view', 'id' => $model->id]);
}
}
return $this->render('create', [
'model' => $model,
]);
}
I get the following error when I submit my CRUD form to create the record:
Cannot redeclare class frontend\components\formatDate\formatDate
1. in "C:\wamp\www\application\frontend\components\formatDate.php" at line 5
this is the line that’s throwing the error:
"class formatDate {"
Can someone help to resolve this error?
Thanks