Prestashop 1.7 - Bug FormBuilder on Cms Page Category - module

I wrote a Prestashop module to add two fields in the CMS Category but the render is wrong.
My source code:
<?php
class NewsSlider extends Module {
public function hookActionCmsPageCategoryFormBuilderModifier(array $params) {
$formBuilder = $params['form_builder'];
$locales = $this->get('prestashop.adapter.legacy.context')->getLanguages();
$formBuilder->add($this->name.'_cover_lang',
\PrestaShopBundle\Form\Admin\Type\TranslatableType::class,
[
'type' => \Symfony\Component\Form\Extension\Core\Type\FileType::class,
'label' => $this->l('Image de couverture'),
'options' => [
'required' => false,
'constraints' => [
'mimeTypes' => [
'image/png',
'image/jpeg'
],
'mimeTypesMessage' => 'JPEG/PNG',
]
],
'required' => false,
]
);
$formBuilder->add($this->name.'_header_lang',
\PrestaShopBundle\Form\Admin\Type\TranslateType::class,
[
'type' => \PrestaShopBundle\Form\Admin\Type\FormattedTextareaType::class,
'label' => $this->l('EntĂȘte de la page'),
'locales' => $locales,
'hideTabs' => false,
'required' => false
]
);
$languages = Language::getLanguages(true);
foreach($languages as $lang){
$content = $this->getCMSHeader($params['id'], $lang['id_lang'], $isCategory);
if(is_string($content) && strlen($content)) {
$params['data'][$this->name.'_header_lang'][$lang['id_lang']] = $content;
}
}
$formBuilder->setData($params['data']);
}
}
?>
You can see the render here.
And I wrote exactly the same code for the CMS Page (hookActionCmsPageFormBuilderModifier) and it's working. Why is it different?

Related

Not Found Page Working On Backend But Not Working at Frontend Yii2

I have yii installed on my live server we have two interfaces one backend and one frontend. In backend we add products and in front end the view is rendered for the products. The problem is that for example this is our website https://mmstore.be/products/714/IPhone-12-Mini-Scherm-Reparatie product page if you put anything at the last of the url like this https://mmstore.be/products/714/IPhone-12-Mini-Scherm-Reparatie/03003300303094949949494 the page will remain the same means it should be showing not found page but the same page comes again.
Below is my config file code frontend.
<?php
$params = array_merge(
require __DIR__ . '/../../common/config/params.php',
require __DIR__ . '/../../common/config/params-local.php',
require __DIR__ . '/params.php',
require __DIR__ . '/params-local.php'
);
return [
'id' => 'app-frontend',
'basePath' => dirname(__DIR__),
'bootstrap' => ['log'],
'controllerNamespace' => 'frontend\controllers',
'components' => [
'request' => [
'csrfParam' => '_csrf-frontend',
],
'cache' => [
'class' => 'yii\caching\FileCache',],
'user' => [
'identityClass' => 'common\models\User',
'enableAutoLogin' => true,
'identityCookie' => ['name' => '_identity-frontend', 'httpOnly' => true],
],
'session' => [
// this is the name of the session cookie used for login on the frontend
'name' => 'advanced-frontend',
],
'log' => [
'traceLevel' => YII_DEBUG ? 3 : 0,
'targets' => [
[
'class' => 'yii\log\FileTarget',
'levels' => ['error', 'warning'],
],
],
],
'errorHandler' => [
'errorAction' => 'site/error',
],
'urlManager' => [
'baseUrl' => '',
'enablePrettyUrl' => false,
'showScriptName' => false,
'enableStrictParsing' => true,
'rules'=>array(
'<controller:\w+>/<id:\d+>' => '<controller>/view',
'<controller:\w+>/<action:\w+>/<id:\d+>' => '<controller>/<action>',
'<controller:\w+>/<action:\w+>' => '<controller>/<action>',
'class' => 'yii\web\UrlNormalizer',
'collapseSlashes' => true,
'normalizeTrailingSlash' => true,
),
],
],
'params' => $params,
];
i have error.php in my site directory and below is its code
<?php
/* #var $this yii\web\View */
/* #var $name string */
/* #var $message string */
/* #var $exception Exception */
use yii\helpers\Html;
$this->title = $name;
?>
<h1><?= Html::encode($this->title) ?></h1>
<div class="alert alert-danger">
<?= nl2br(Html::encode($message)) ?>
</div>
<p>
The above error occurred while the Web server was processing your request.
</p>
<p>
Please contact us if you think this is a server error. Thank you.
</p>
It is strange that you disabled "enablePrettyUrl", and using pretty url. If "/products/" is a controller name and assuming "IPhone-12-Mini-Scherm-Reparatie" is a parameter named "url" then you can change urlManager like this:
'urlManager' => [
'enablePrettyUrl' => true,
'showScriptName' => false,
'rules' => [
'/'=>'site/index',
'/products/<id>/<url>'=>'products/view',
'/products/<id>'=>'products/view',
'<controller:\w+>/<action:\w+>' => '<controller>/<action>',
],
],
in controller it should be something like this
public function actionView($id, $url) {
$product = Product::find()->where(['id'=>$id])->one();
// ...
}

access to subfolders controller and view in YII2

hi i built a controller in a folder inside controllers folder
i tryed to access my controller and its view but i couldnt always error 404
please tell me what is the problem
here is the details
this is SiteUserController in Controllers/userzone/ folder
namespace app\controllers\userzone;
use yii\web\Controller;
use app\models\UserZone;
/**
* Default controller for the `dashboard` module
*/
class SiteUserController extends Controller
{
/**
* Renders the index view for the module
* #return string
*/
public function actionIndex()
{
$id = \Yii::$app->user->id;
$model = UserZone::find()->where(['id_zone'=>$id])->with('user')->one();
// $model->joinWith('companiesCompany');
return $this->render('siteuser/index',[
'model'=>$model
]);
}
}
the view file is in Views/siteuser/index.php directory .
i changed url manager to
'urlManager' => [
'enablePrettyUrl' => true,
'showScriptName' => false,
'rules' => [
'userzone/<controller:\w+>/<action:\w+>'=>'userzone/<controller>/<action>',
],
],
In Controller:
return $this->render('index',[
'model'=>$model
]);
Its Working
You need to change you controllerNamespace in config/main file i.e. below code for config/main.php
<?php
$params = array_merge(
require(__DIR__ . '/../../common/config/params.php'),
require(__DIR__ . '/../../common/config/params-local.php'),
require(__DIR__ . '/params.php'),
require(__DIR__ . '/params-local.php')
);
return [
'id' => 'app-frontend',
'basePath' => dirname(__DIR__),
'bootstrap' => ['log'],
'controllerNamespace' => 'app\controllers\userzone', //here is your controller path
'components' => [
'view' => [
'theme' => [
'pathMap' => [
'#frontend/views' => '#themes/frontend/views',
],
],
],
'request' => [
'csrfParam' => '_csrf-frontend',
],
'user' => [
'identityClass' => 'common\models\User',
'enableAutoLogin' => true,
'identityCookie' => ['name' => '_identity-frontend', 'httpOnly' => true],
],
'session' => [
// this is the name of the session cookie used for login on the frontend
'name' => 'advanced-frontend',
],
'log' => [
'traceLevel' => YII_DEBUG ? 3 : 0,
'targets' => [
[
'class' => 'yii\log\FileTarget',
'levels' => ['error', 'warning'],
],
],
],
'errorHandler' => [
'errorAction' => 'site/error',
],
/*
'urlManager' => [
'enablePrettyUrl' => true,
'showScriptName' => false,
'rules' => [
],
],
*/
],
'params' => $params,
];

Not able to submit form inside footer in Yii2

I've a subscribe newsletter form inside footer that display on all page. To do this I've created a subscriber widget like this:
SubscriberWidget.php
<?php
namespace frontend\components;
use Yii;
use yii\base\Widget;
use yii\helpers\Html;
use frontend\models\SubscribeNewsletterForm;
class SubscriberWidget extends Widget
{
public function run()
{
$subscriber_model = new SubscribeNewsletterForm();
return $this->render('_subscribe-newsletter-form.php', [
'subscriber_model' => $subscriber_model
]);
}
}
?>
Here's the SubscribeNewsletterForm model code:
SubscribeNewsletterForm.php
<?php
namespace frontend\models;
use Yii;
use yii\base\Model;
class SubscribeNewsletterForm extends Model
{
public $email;
public function rules()
{
return [
[['email'], 'required'],
['email', 'email']
];
}
}
?>
Here is the code of my _subscribe-newsletter-form.php
<?php
use yii\helpers\Html;
use yii\bootstrap\ActiveForm;
use yii\helpers\Url;
?>
<h3>Subscribe to Newsletter</h3>
<?php $form = ActiveForm::begin(['id' => $subscriber_model->formName(), 'action' => ['project/subscriber'], 'validateOnBlur' => false, 'validateOnType' => false]); ?>
<div class="input-group">
<?= $form->field($subscriber_model, 'email')->textInput()->label(false); ?>
<span class="input-group-btn">
<?php echo Html::submitButton('Sign Up', ['class' => 'btn btn-primary subscribe-btn']); ?>
</span>
</div>
<?php ActiveForm::end(); ?>
<?php
$script = <<< JS
$('#{$subscriber_model->formName()}').on('beforeSubmit', function(e){
var form = $(this);
$.post(
form.attr("action"),
form.serialize()
).done(function(data){
form.trigger("reset");
})
return false;
});
JS;
$this->registerJs($script);
?>
Inside ProjectController.php I've created the action as follow:
public function actionSubscriber()
{
$subscriber_model = new SubscribeNewsletterForm();
$request = Yii::$app->request;
if($request->isAjax && $subscriber_model->load($request->post())){
$subscriber = new Subscriber([
'email' => $subscriber_model->email
]);
$subscriber->save();
}
}
Here's the Subscriber model code.
Subscriber.php
<?php
namespace frontend\models;
use yii\db\ActiveRecord;
class Subscriber extends ActiveRecord
{
public static function tableName()
{
return 'subscriber';
}
}
?>
frontend/config/main.php
<?php
$params = array_merge(
require(__DIR__ . '/../../common/config/params.php'),
require(__DIR__ . '/../../common/config/params-local.php'),
require(__DIR__ . '/params.php'),
require(__DIR__ . '/params-local.php')
);
return [
'id' => 'app-frontend',
'basePath' => dirname(__DIR__),
'bootstrap' => ['log'],
'controllerNamespace' => 'frontend\controllers',
'components' => [
'request' => [
'csrfParam' => '_csrf-frontend',
],
'user' => [
'identityClass' => 'common\models\User',
'enableAutoLogin' => true,
'identityCookie' => ['name' => '_identity-frontend', 'httpOnly' => true],
],
'session' => [
// this is the name of the session cookie used for login on the frontend
'name' => 'advanced-frontend',
],
'log' => [
'traceLevel' => YII_DEBUG ? 3 : 0,
'targets' => [
[
'class' => 'yii\log\FileTarget',
'levels' => ['error', 'warning'],
],
],
],
'errorHandler' => [
'errorAction' => 'site/error',
],
/*
'urlManager' => [
'enablePrettyUrl' => true,
'showScriptName' => false,
'rules' => [
],
],
*/
],
'params' => $params,
];
?>
With above code validation is working but i'm not able to save the email in database. Please tell what i'm doming wrong.
You need rules on your Model. Also, I always replace the generated tables names with the table prefix supported method. Also, I always like to use the Timestamp behavior to log when things are created or updated. Especially when your grabbing contact info for the use of leads, I would record the timestamps as well as their IP Address.
Subscriber.php
use yii\behaviors\TimestampBehavior;
// ...
/**
* #inheritdoc
*/
public static function tableName()
{
return '{{%subscriber}}';
}
/**
* #inheritdoc
*/
public function behaviors()
{
return [
TimestampBehavior::className(),
];
}
/**
* #inheritdoc
*/
public function rules()
{
return [
['email', 'filter', 'filter' => 'trim'],
['email', 'required'],
['email', 'email'],
['email', 'string', 'max' => 255],
['email', 'unique', 'targetClass' => '\common\models\Subscriber', 'message' => 'This email address has already been taken.'],
[['created_at', 'updated_at'], 'integer'],
];
}

Automatically refreshing yii2 grid after server database changes

I have a grid that involves truck verification. I would like the contents of the grid to change without page refresh.
Currently this works when the page is refreshed but i would like it to work even when a page is not refreshed that is when the content changes in the server database.
This is the grid
<?php
$gridColumns = [
['class' => 'kartik\grid\SerialColumn'],
'reg_no',
[
'attribute'=>'truck_category',
'value'=>'truckCategory.category'
],
[
'class' => 'kartik\grid\ActionColumn',
'vAlign'=>'middle',
'urlCreator' => function($action, $model, $key, $index) { return '#'; },
'viewOptions'=>['title'=>"vdgdv", 'data-toggle'=>'tooltip'],
'updateOptions'=>['title'=>"update", 'data-toggle'=>'tooltip'],
'deleteOptions'=>['title'=>"delete", 'data-toggle'=>'tooltip'],
]
];
echo GridView::widget([
'dataProvider' => $dataProvider,
'filterModel' => $searchModel,
'columns' => $gridColumns,
'containerOptions' => ['style'=>'overflow: auto'], // only set when $responsive = false
'beforeHeader'=>[
[
'options'=>['class'=>'skip-export'] // remove this row from export
]
],
'toolbar' => [
[],
'{export}',
'{toggleData}'
],
'pjax' => true,
'bordered' => true,
'striped' => false,
'condensed' => false,
'responsive' => true,
'hover' => true,
'floatHeader' => true,
'showPageSummary' => true,
'panel' => [
'type' => GridView::TYPE_PRIMARY
],
]);
?>
This is the controller that renders the grid
public function actionTrackingcenter()
{
$query = Truck::find()->where(['truck_status'=>5]);
$searchModel = new TruckSearch();
$dataProvider = $searchModel->search(Yii::$app->request->queryParams,$query);
return $this->render('trackingcenter/index', [
'searchModel' => $searchModel,
'dataProvider' => $dataProvider,
]);
}
Could someone give a direction on how i can achieve the automatic change
You can use below with set-time-interval with jQuery
<?php
$this->registerJs('
setInterval(function(){
$.pjax.reload({container:"YOUR_PJAX_CONTAINER_ID"});
}, 10000);', \yii\web\VIEW::POS_HEAD);
?>
This code will be place after your GridView code
This will be reload your Pjax grid every 10 second

How to display Image in gridview yii2

I'm new to yii, i want to display an image in gridview table, anyhelp will be appreciated, below is my code.
view....
<?= GridView::widget([
'dataProvider' => $dataProvider,
//'filterModel' => $searchModel,
'columns' => [
//['class' => 'yii\grid\SerialColumn'],
'product_id',
'name',
'descr',
'price',
//'image',
[
'attribute'=>'image',
'label'=>'Image',
'format'=>'html',
'value' => function ($data) {
$url = \Yii::getAlias('#backend/web/').$data['image'];
return Html::img($url, ['alt'=>'myImage','width'=>'70','height'=>'50']);
}
],
'views',
['class' => 'yii\grid\ActionColumn'],
],
'tableOptions' =>['class' => 'table table-striped table-bordered'],
I'm using dataProvider and below is my controller
public function actionIndex()
{
$searchModel = new ProductSearch();
$dataProvider = $searchModel->search(Yii::$app->request->queryParams);
//$models = $dataProvider->getModels();
return $this->render('index', [
'searchModel' => $searchModel,
'dataProvider' => $dataProvider,
//'models' => $models,
]);
}
The above code is not working fine no image display only the img alt shown
Any help on how to get this work, thanks
Here is the solution :
[
'attribute' => 'Icon',
'format' => 'html',
'label' => 'Icon',
'value' => function ($data) {
return Html::img(Yii::$app->request->BaseUrl.'/uploads/path/' . $data['Icon'],
['width' => '60px']);
},
],
Check you image path,
You can use
Yii::$app->request->baseUrl
If your index file is on root directory
$url =Yii::$app->request->baseUrl.'/'.$data['image'];
Specify 'format' to 'raw' for image column and $data should be and object, so 'image' field is accessible with $data->image.
[
'attribute'=>'image',
'label'=>'Image',
'format'=>'raw',
'value' => function ($data) {
$url = \Yii::getAlias('#backend/web/').$data->image;
return Html::img($url, ['alt'=>'myImage','width'=>'70','height'=>'50']);
}
],