this is my _form.php :
<?php
use dosamigos\fileupload\FileUploadUI;
// with UI
?>
<?=
FileUploadUI::widget([
'model' => $model,
'attribute' => 'image',
'url' => ['media/upload', 'id' => 'image'],
'gallery' => false,
'fieldOptions' => [
'accept' => 'image/*'
],
'clientOptions' => [
'maxFileSize' => 200000
],
// ...
'clientEvents' => [
'fileuploaddone' => 'function(e, data) {
console.log(e);
console.log(data);
}',
'fileuploadfail' => 'function(e, data) {
console.log(e);
console.log(data);
}',
],
]);
?>
my file uploaded in my host but i need that url
this is my product controller and image is empty :
public function actionCreate()
{
$request = Yii::$app->request;
$model = new Product();
$idCon = Yii::$app->user->id;
$model->user_id = $idCon;
if ($request->isAjax)
{
/*
* Process for ajax request
*/
Yii::$app->response->format = Response::FORMAT_JSON;
if ($request->isGet)
{
return [
'title' => "Create new Product",
'content' => $this->renderAjax('create', [
'model' => $model,
]),
'footer' => Html::button('Close', ['class' => 'btn btn-default pull-left', 'data-dismiss' => "modal"]) .
Html::button('Save', ['class' => 'btn btn-primary', 'type' => "submit"])
];
}
else if ($model->load($request->post()) && $model->save())
{
return [
'forceReload' => '#crud-datatable-pjax',
'title' => "Create new Product",
'content' => '<span class="text-success">Create Product success</span>',
'footer' => Html::button('Close', ['class' => 'btn btn-default pull-left', 'data-dismiss' => "modal"]) .
Html::a('Create More', ['create'], ['class' => 'btn btn-primary', 'role' => 'modal-remote'])
];
}
else
{
return [
'title' => "Create new Product",
'content' => $this->renderAjax('create', [
'model' => $model,
]),
'footer' => Html::button('Close', ['class' => 'btn btn-default pull-left', 'data-dismiss' => "modal"]) .
Html::button('Save', ['class' => 'btn btn-primary', 'type' => "submit"])
];
}
}
else
{
/*
* Process for non-ajax request
*/
if ($model->load($request->post()) && $model->save())
{
return $this->redirect(['view', 'id' => $model->id]);
}
else
{
return $this->render('create', [
'model' => $model,
]);
}
}
}
and this is my model :
use Yii;
use yii\web\UploadedFile;
use yii\base\Model;
/**
* This is the model class for table "product".
*
* #property integer $id
* #property string $name
* #property string $price
* #property string $image
* #property string $url
* #property integer $user_id
*
* #property ConProduct[] $conProducts
* #property User $user
* #property Sales[] $sales
*/
class Product extends \yii\db\ActiveRecord
{
/**
* #inheritdoc
*/
public static function tableName()
{
return 'product';
}
/**
* #inheritdoc
*/
public function rules()
{
return [
[['price'], 'number'],
[['user_id'], 'integer'],
[['name', 'image'], 'string', 'max' => 300],
[['url'], 'string', 'max' => 255],
[['user_id'], 'exist', 'skipOnError' => true, 'targetClass' => User::className(), 'targetAttribute' => ['user_id' => 'id']],
];
}
how can i get image url with $model->image in controller !?
Have you tried to use yii\web\UploadedFile::getInstance()?
$model->image = UploadedFile::getInstance($model, 'image');
if ($model->upload()) {
// do some stuff with file
}
http://www.yiiframework.com/doc-2.0/guide-input-file-upload.html#wiring-up
Related
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?
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'],
];
}
I think I got a mistake in the Authorization of my App. I want only to allow to add Pages by users with an admin role. But I can access the add function with no problem. So here is what I did.
AppController
public function initialize()
{
parent::initialize();
$this->loadComponent('RequestHandler');
$this->loadComponent('Flash');
$this->loadComponent('Auth', [
'loginRedirect' => [
'controller' => 'Moves',
'action' => 'view'
],
'logoutRedirect' => [
'controller' => 'Pages',
'action' => 'display',
'home'
]
]);
public function beforeFilter(Event $event)
{
$this->Auth->allow(['index', 'view', 'display', 'english', 'italian', 'german']);
$this->Auth->loginAction = array('controller'=>'pages', 'action'=>'home');
$this->loadModel('Menus');
$main_de = $this->Menus->find('all', array(
'conditions' => array('Menus.action' => 'main_de')
));
$this->set('main_de', $main_de);
$main_us = $this->Menus->find('all', array(
'conditions' => array('Menus.action' => 'main_us')
));
$this->set('main_us', $main_us);
}
public function isAuthorized($user)
{
// Admin can access every action
if (isset($user['role']) && $user['role'] === 'admin') {
return true;
}
// Default deny
return false;
}
Pages
public function isAuthorized($user)
{
// All registered users can add articles
if ($this->request->action === 'add') {
return false;
}
// The owner of an article can edit and delete it
if (in_array($this->request->action, ['edit', 'delete'])) {
$articleId = (int)$this->request->params['pass'][0];
if ($this->Articles->isOwnedBy($articleId, $user['id'])) {
return false;
}
}
return false;
}
I fixed the problem by adding 'authorize' => 'Controller', to the Auth Array
public function initialize()
{
parent::initialize();
$this->loadComponent('RequestHandler');
$this->loadComponent('Flash');
$this->loadComponent('Auth', [
'loginRedirect' => [
'controller' => 'Moves',
'action' => 'view'
],
'logoutRedirect' => [
'controller' => 'Pages',
'action' => 'display',
'home'
],
// **'authorize' => 'Controller',**
]);
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']);
}
],
the gridview if on right of the page,left is some menus,when click on page no 2,it dose not only refresh the gridview,but all page including left part are lost——a totally new page come out!help~
there is the debugging Screenshot:
my action is
public function actionList()
{
$model = new Loan();
$dataProvider = new ActiveDataProvider([
'query' => $model->find(),
'pagination' => [
'pagesize' => '1',
],
]);
return $this->renderPartial('list', ['model' => $model, 'dataProvider' => $dataProvider]);
}
my view is:
<?php
use yii\grid\GridView;
use yii\grid\SerialColumn;
use yii\helpers\Html;
use yii\helpers\Url;
use yii\widgets\LinkPager;
?>
<?=GridView::widget([
'dataProvider' => $dataProvider,
'layout'=> '{items}{pager}',
'columns' => [
['attribute' =>'loan_type','label'=>'借款类型','options' => ['width' => '80']],
['attribute' =>'amount','label'=>'金额','options' => ['width' => '80']],
['attribute' =>'rate','label'=>'还款利率','options' => ['width' => '80']],
['attribute' =>'fee','label'=>'手续费','options' => ['width' => '80']],
['attribute' =>'status','label'=>'状态','options' => ['width' => '80'] ],
['attribute' =>'comment','label'=>'审核意见','options' => ['width' => '80']],
['attribute' => 'created_at','value' =>function($model){return date('Y-m-d',strtotime($model->created_at));},'label'=>'申请时间','options' => ['width' => '150']],
[
'class' => 'yii\grid\ActionColumn',
'header' => '操作',
'template' => '{audit}',
'buttons' => [
'audit' => function ($url,$model) {
return Html::a('<span id="xxxx" class="glyphicon glyphicon-user"></span>','#',['title'=>'审核',
'onclick'=>"
$.ajax({
type: 'GET',
dataType: 'text',
url: 'http://182.92.4.87:8000/index.php?r=loan/pj', //目标地址
error: function (XMLHttpRequest, textStatus, errorThrown) {alert(XMLHttpRequest.status + ':' + XMLHttpRequest.statusText); },
success: function (page)
{
$('.ucRight').html(page);
}
});
return false;",
]);},
],
'urlCreator' => function ($action, $model, $key, $index) {
return Yii::$app->getUrlManager()->createUrl(['loan/list','id' => $model->status]);
},
'headerOptions' => ['width' => '80'],
],
],
]);
?>
The reason for your problem is that you haven't prevented the html link from directing to a new page, so your user is clicking on the link, which then loads a new page with the contents returned by the server; in this case a page of information with no layout applied. You need to add event.preventDefault() before the ajax call to stop this behaviour.
However, as #arogachev said, if you simply want to use pagination without a page refresh, then just use pjax. That is what pjax is designed for,