I have a problem with Yii export library. I just follow the documentation in this link: https://github.com/moonlandsoft/yii2-phpexcel , output have come out like encoding views.
my code view:
\moonland\phpexcel\Excel::export([
'isMultipleSheet' => true,
'models' => [
'sheet1' => Order::find()->all(),
], 'columns' => [
'sheet1' => ['id','phone','total'],
],
'headers' => [
'sheet1' => ['column1' => 'id','column2' => 'phone', 'column3' => 'total']
],
]);
You've got the xlsx file source directly embeded into your web page, because you didn't send proper headers. Your view template is fine but your controller action should look like this:
public function actionExport()
{
//set headers to prevent caching
$headers = \Yii::$app->response->headers;
$headers->set('Expires', 'Mon, 1 Apr 1974 05:00:00 GMT');
$headers->set('Last-Modified', gmdate("D,d M YH:i:s") . " GMT");
$headers->set('Cache-Control', 'no-cache, must-revalidate');
$headers->set('Pragma', 'no-cache');
//use renderPartial instead of render because we don't want to add layout
$content = $this->renderPartial('export');
//send content as attachment with filename my-export.xlsx and proper mime type
return \Yii::$app->response->sendContentAsFile(
$content,
'my-export.xlsx',
['mimeType' => 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet']
);
}
Related
I am trying to build a dynamic page system with cakephp 3.
Using slugs I can show pages and content. But on the homepage, it is just using the default view template.
I have the routes as followed:
$routes->connect('/', ['controller' => 'pages', 'action' => 'display', 'home']);
$routes->connect('/:slug', ['controller' => 'pages', 'action' => 'view'], ['pass' => ['slug'], 'slug' => '[^\?/]+']);
Which works for the none homepage pages.
But I want to use the homepage as / (e.g. localhost:8000/)
And not /home (e.g. localhost:8000/home).
Currently the view function in the pages controller looks like this:
public function view($slug = null)
{
$pages = TableRegistry::getTableLocator()->get('webpages');
$page = $pages->findBySlug($slug)->firstOrFail();
$this->set(compact('page'));
}
Any idea?
Seems I already found the solution.
I changed the routing to just the following line:
$routes->connect('/*', ['controller' => 'pages', 'action' => 'view']);
Then I changed the view as followed:
public function view($slug = null)
{
$pages = TableRegistry::getTableLocator()->get('webpages');
if($slug == null){
$query = $pages->find('all', [
'conditions' => ['ishome' => 1]
]);
} else {
$query = $pages->find('all', [
'conditions' => ['slug' => $slug]
]);
}
$page = $query->first();
$this->set(compact('page'));
}
I use the answer from the following comment, but had to modify it a bit, since that code was used for an older version of cakephp (I am using cakekphp 3.8).
https://stackoverflow.com/a/3975923/6181243
I am using the mpdf extension to generate pdf files. I have set global settings for the mpdf in the config file, hence I am able to call the function every time I want to generate a pdf from my controller action. However, I am finding it hard to change the orientation for the pdf with data that requires landscape orientation since the default orientation set in the global settings is portrait. Here are the codes:
main.pdf code for the global setting
'pdf' => [
'class' => Pdf::classname(),
'mode' => Pdf::MODE_UTF8, // leaner size using standard fonts
'format' => Pdf::FORMAT_A4,
'orientation' => Pdf::ORIENT_PORTRAIT,
'destination' => Pdf::DEST_BROWSER,
'cssFile' => '#vendor/kartik-v/yii2-mpdf/assets/kv-mpdf-bootstrap.min.css',
// any css to be embedded if required
'cssInline' => '.kv-heading-1{font-size:18px}',
'options' => [
'shrink_tables_to_fit' => 0
],
// refer settings section for all configuration options
],
Controller Action calling the global settings:
public function actionReservationsList()
{
$searchModel = new ReservationsSearch();
$dataProvider = $searchModel->search(Yii::$app->session->get('repquery'));
$dataProvider->pagination = false;
$pdf = Yii::$app->pdf;
$pdf->content = $this->renderPartial('index', [
'searchModel' => $searchModel,
'dataProvider' => $dataProvider,
]);
$pdf->methods = [
'SetHeader' => [Yii::$app->user->identity->company->name.'||Date: ' . date("r")],
'SetFooter' => ['User: '.Yii::$app->user->identity->username.'||Page {PAGENO}'],
];
return $pdf->render();
}
So I need help in overriding the 'orientation' => Pdf::ORIENT_PORTRAIT, setting that is in the global settings main.php file from the controller action.
This work for me:
<?php
namespace backend\controllers;
use Yii;
use yii\web\Controller;
use kartik\mpdf\Pdf;
class InformesController extends Controller
{
...
public function actionImprimirInforme($id,$key)
{
$html = $this->renderPartial('informe-pdf', [
'title' => 'Informe'
]);
$pdf = new Pdf([
'format' => Pdf::FORMAT_A4,
'orientation' => Pdf::ORIENT_LANDSCAPE,
'destination' => Pdf::DEST_BROWSER,
'options' => [
'showImageErrors' => true,
]
]);
$pdf->configure([
'title' => 'Informe ',
]);
$pdf->content = $html;
$pdf->orientation = Pdf::ORIENT_LANDSCAPE;
$pdf->execute('SetFooter', ['{PAGENO} de {nbpg}']);
$pdf->filename = "Informe.pdf";
return $pdf->render();
}
}
My first answer was wrong, i have been setting the property 'orientation' into pdf component, so the dynamically assign does not work properly.
Here you have the documentation example
You need to add the contents via addPage. So if you build a array of pages, with the contents etc - you should be able to specify the orientation per page.
<?php
$mpdf = new mPDF('', 'Legal');
$mpdf->WriteHTML('
Hello World
');
$mpdf->AddPage('L'); // Adds a new page in Landscape orientation
$mpdf->WriteHTML('
Hello World
');
$mpdf->Output();
?>
Try add this line this :
$pdf = Yii::$app->pdf;
$pdf->orientation = Pdf::ORIENT_LANDSCAPE;
I made a Zend Framework 3 MVC application. I don't want a default router. My one controller RESTFUL and only returning JSON. I want to remove the default IndexController. I want / to just give a 404 error. I'd prefer not to call any route 'home' but will do that if necessary.
If I make my route config look like this:
'router' => [
'routes' => [
'myRoute' => [
'type' => Segment::class,
'options' => [
'route' => '/myThing[/:action]',
'defaults' => [
'controller' => Controller\MyThingController::class,
'action' => 'index',
],
],
],
],
],
I get the following exception when I connect to a route that worked when I kept the default index controller in my browser:
Fatal error: Uncaught Zend\Router\Exception\RuntimeException: Route with name "home" not found in /var/www/vendor/zendframework/zend-router/src/Http/TreeRouteStack.php on line 354
If I change 'myRoute' => [ to 'home' => [ It renders the default layout instead of the Json rendered by JsonViewModel.
I just put an IndexController with a default route that renders the defautl 404 page for now. I'm going to make it return JSON at some point when I figure out how.
class IndexController extends AbstractRestfulController
{
public function indexAction()
{
$this->response->setStatusCode(Response::STATUS_CODE_404);
}
}
I'm not sure if this is what your after but to return a json response from your controller use.
In your module config:
'view_manager' => array(
'strategies' => array(
'ViewJsonStrategy',
),
},
and in your controller:
use Zend\View\Model\JsonModel;
// ...
public function indexAction()
{
$this->response->setStatusCode(Response::STATUS_CODE_404);
$view = new JsonModel();
$view->jsonVariable = 'someValue';
return $view;
}
This will return a json response.
Hope this helps.
i'm building multi lingual site with English and Arabic
url for English
url for Arabic
I want to switch language from any page exactly to the same page of the other language
so i made code like below.
$route = Yii::$app->controller->route;
$params = $_GET;
array_unshift($params, '/'.$route);
<?php if(Yii::$app->language == 'ar'){ ?>
<?= Html::a('English', [Yii::$app->urlManager->createUrl($params), 'language'=>'en']); ?>
<?php }else{?>
<?= Html::a('Arabic', [Yii::$app->urlManager->createUrl($params), 'language'=>'ar']); } ?>
and my url generating like below
/multi/backend/web/en/multi/backend/web/ar/site/index?val=hii&net=good
English
don't know what is wrong?
I'm using this for language management.
please check my main.php under backend/config
<?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-backend',
'basePath' => dirname(__DIR__),
'controllerNamespace' => 'backend\controllers',
'language' => 'en',
'sourceLanguage' => 'en_UK',
'bootstrap' => ['log'],
'modules' => [],
'components' => [
'user' => [
'identityClass' => 'common\models\User',
'enableAutoLogin' => true,
],
'log' => [
'traceLevel' => YII_DEBUG ? 3 : 0,
'targets' => [
[
'class' => 'yii\log\FileTarget',
'levels' => ['error', 'warning'],
],
],
],
'errorHandler' => [
'errorAction' => 'site/error',
],
'i18n' => [
'translations' => [
'app' => [
'class' => 'yii\i18n\DbMessageSource',
'sourceLanguage' => 'en_UK',
],
],
],
'urlManager' => [
'class' => 'codemix\localeurls\UrlManager',
'languages' => ['en', 'ar'],
'enableDefaultLanguageUrlCode' => false,
'enablePrettyUrl' => true,
'showScriptName' => false,
'rules' => [
],
],
],
'params' => $params,
];
If you are doing it as in your example, you have to think about it on every link you create. This can be automated easily.
URL-Rule
You can solve this with an url-rule in your config file like so:
'<language:[\w]{2,2}>/<controller:\w+>/<action:\w+>'=>'<controller>/<action>',
This will assert the proper routing to your controller and provide you the desired language in the language-variable.
Custom UrlManager
You can extend the UrlManager-class and make sure the current language is always appended to the params:
class MyUrlManager extends \yii\web\UrlManager
{
// ...
/**
* #inheritdoc
*/
public function createUrl($params)
{
if (!isset($params['language'])) {
$params['language'] = Yii::$app->language;
}
return parent::createUrl($params);
}
// ...
}
This will automate the process of adding the language to the links you create.
Custom Application
Now you should also override the Application-class and always set the language to the one provided or choose a default (in this case en):
class MyApplication extends \yii\web\Application
{
// ...
/**
* #inheritdoc
*/
public function init()
{
parent::init();
$lang = Yii::$app->request->get('language', 'en');
Yii::$app->language = $lang;
}
// ...
}
Now your language will always be set to the default value or the one provided viathe query param as specified above.
Final thoughts
This should give you the basic idea on how to solve your problem. Adjust as necessary...especially the last part with the Application-class and how you retrieve the value of the language-var. I hope it helped!
Possible problems with your code and the extension provided
If you read the docs of the extension the urls are generated differently. It tells you to create the urls as follows:
Url::to(['demo/action', 'language'=>'ar'])
You are createing a simple link-tag and overwrite the $params. Try this instead:
echo Html::a('Arabic', Url::to(['site/index', 'language'=>'ar']));
For redirection to the current page just replace the first part with the current route.
after lots of trying ..i found a solution.. now its worked for me.
$route = Yii::$app->controller->route;
if(Yii::$app->language == 'ar'){
$_GET['language'] = 'en';
}else{
$_GET['language'] = 'ar';
}
$params = $_GET;
array_unshift($params, '/'.$route);
<?php if(Yii::$app->language == 'ar'){ ?>
<?= Html::a('English', Yii::$app->urlManager->createUrl($params)); ?>
<?php }else{?>
<?= Html::a('Arabic', Yii::$app->urlManager->createUrl($params)); } ?>
its working for the url like
http://localhost/multi/backend/web/site/index?page=2&per-page=6
and
http://localhost/multi/backend/web/site/index
I have been assigned to integrate API for my client website. This API is provided by vision6.com.au. There is no much information avialble on their website. Can anyone give me one example which will contact vision6 database and add a contact from our website developed using jquery and php.
Here is the way I am trying
var newVal = {
"id": 1,
"method": "addUser",
"params": [
"APIKEY",
"123456",
{
"username" : "username_123",
"password" : "123456abc",
"first_name" : "First Name",
"last_name" : "Last Name",
"email" : "example#example.com",
"mobile" : "0412312312",
"phone" : "56565656",
"fax" : "57575757",
"position" : "Manager",
"is_read_only" : true,
"timezone" : "Australia/Brisbane",
"email_user" : true,
"is_confirmed" : true
}
]
};
$.ajax({
url: 'http://www.vision6.com.au/api/jsonrpcserver.php?version=3.0',
type: 'POST',
beforeSend: function(){alert('sending');},
data: newVal,
//dataType: 'json',
//data: JSON.stringify(newVal),
//contentType: 'application/json; charset=utf-8',
dataType: 'json',
//async: false,
success: function(msg) { alert(msg);
}
});
This is what I have taken from their documentation
developers.vision6.com.au
For those who wants to integrate using Ruby, I've created a gist with a simple code:
require 'httparty'
url = 'http://www.vision6.com.au/api/jsonrpcserver.php?version=3.0'
api_key = 'xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx'
JSON.parse(HTTParty.post(url, headers: { 'Content-Type' => 'application/json' }, body: JSON.dump({
'method' => 'getSessionInfo', 'params' => [api_key]
})))
JSON.parse(HTTParty.post(url, headers: { 'Content-Type' => 'application/json' }, body: JSON.dump({
'method' => 'searchLists', 'params' => [api_key]
})))
list_id = 123456
JSON.parse(HTTParty.post(url, headers: { 'Content-Type' => 'application/json' }, body: JSON.dump({
'method' => 'addContacts', 'params' => [api_key, list_id, [{ 'First Name' => 'Foo', 'Last Name' => 'Bar', 'Email' => 'foo#bar.com' }]]
})))
You will need to download a jsonRPCClient.php and include it in your php file. From my dealings with the Vision6 API, its not very comprehensive and doesn't make much sense until you start getting into it more. Unfortunately, they aren't very helpful in getting you started.
My code to get you started
include 'includes/jsonRPCClient.php';
$list_id = 1234;
$url = "http://www.vision6.com.au/api/jsonrpcserver.php?version=3.0";
$apikey = 'YOURAPIKEYHERE'
$api = new JsonRpcClient($url);
$contact = array();
$contact[] = array(
'First Name' => "John",
'Email' => "sample#email.com"
);
$returnID = $api->addContacts($apikey, $list_id, $contact);
the most important change I found was
$api->addContacts($apikey, $list_id, $contact);
All methods using the API follow this structure
$api ->APIMethod($apikey, $OtherRequiredFields/Arrays);
I suggest to follow their documentation
http://developers.vision6.com.au/3.0/guide/getting-started
Documentation mentions a client library to access their JSON-RPC. Download it, create a free account and generate a working snippet of PHP code from their examples. It also seems to contain a lot of insights and examples. I am just quoting PHP code for addbatch
// setup vars
$list_id01 = 123;
$list_id02 = 456;
$message_id = 111;
$batch_details = array
(array
('list_id' => $list_id01,
'type' => 'list', // all Contacts in List 123
'time' => 'send, // populate Batch time of send
)
array
('list_id' => $list_id02,
'type' => 'contact', // send to contact_list, next
'contact_list' => array(2),array(17),array(18),
'time' => 'send, // populate Batch time of send
));
$queue_id = $api->invokeMethod('addBatch', $message_id, $batch_details,
time() + (24*3600), true);
Once you produce a snippet of code that does an authorization request and a simple action, but DOES NOT behave as you expected you should update your question on SO. I.e. you should post the snippet and the results that you get vs. the results that you expect to get. That might really help to tackle the problem.
I would also recommend to contact support of the service directly.
PS
Unless you will be able to ask a question in form that would be potentially useful to other users, It would be very difficult to get an answer that you seek. Otherwise your question can be qualified as too localized.
<?php
$data = array(www.mtalkz.com)
‘dest’ => ‘0000000000’,
‘msg’=>’This is Test message’,
‘pass’=>’xyz’,
‘send’=>’ALERTS’,
‘uname’=>’ xyz ‘,
‘wapurl’=>’www.mtalkz.com‘
);
$curl = curl_init();
curl_setopt_array($curl, array(
CURLOPT_URL => “https://mtalkz.com/developer-tools/“,
CURLOPT_RETURNTRANSFER => true,
CURLOPT_ENCODING => “”,
CURLOPT_MAXREDIRS => 10,
CURLOPT_TIMEOUT => 30,
CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
CURLOPT_CUSTOMREQUEST => “POST”,
CURLOPT_POSTFIELDS => $data,
CURLOPT_HTTPHEADER => array(
“cache-control: no-cache”,
“content-type: multipart/form-data”,
),
));
$response = curl_exec($curl);
$err = curl_error($curl);
curl_close($curl);
if ($err) {
echo “cURL Error #:” . $err;
} else {
echo $response;
}
<?php
$data = array(www.mtalkz.com)
‘dest’ => ‘0000000000’,
‘msg’=>’This is Test message’,
‘pass’=>’xyz’,
‘send’=>’ALERTS’,
‘uname’=>’ xyz ‘,
‘wapurl’=>’www.mtalkz.com‘
);
$curl = curl_init();
curl_setopt_array($curl, array(
CURLOPT_URL => “https://mtalkz.com/developer-tools/“,
CURLOPT_RETURNTRANSFER => true,
CURLOPT_ENCODING => “”,
CURLOPT_MAXREDIRS => 10,
CURLOPT_TIMEOUT => 30,
CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
CURLOPT_CUSTOMREQUEST => “POST”,
CURLOPT_POSTFIELDS => $data,
CURLOPT_HTTPHEADER => array(
“cache-control: no-cache”,
“content-type: multipart/form-data”,
),
));
$response = curl_exec($curl);
$err = curl_error($curl);
curl_close($curl);
if ($err) {
echo “cURL Error #:” . $err;
} else {
echo $response;
}