понедельник, 8 декабря 2008 г.

Учебник: Grid PHP SQL Часть 11

Печать вашей таблицы.

Отлично... Я собираюсь сказать одну вещь до того, как буду заспамлен тоннами писем с критикой... Метод, описанный здесь для печати вашей таблицы не единственно возможный и не самый оригинальный. Это просто быстрый пример того, как можно распечатать таблицу.

Наш метод - это просто создание HTML файла и заполнение его массивом, содержащим отображаемые в таблице данные (все данные, не только 15 выведенных в данный момент)

Во-первых, мы добавим кнопку Print на нашу панель инструментов:


         ,'-', {
text: 'Print',
tooltip: 'Print me!',
handler: printListing,
iconCls:'print' // defined in our css
}


Давайте теперь определим функцию printListing(). Эта функция вызовет php функцию которая создаст HTML файл таблицы:

    function printListing(){
var searchquery = "";
var searchfirstname = "";
var searchlastname = "";
var searchparty = "";
var searchenteringoffice = "";
var searchleavingoffice = "";
var win; // our popup window
// check if we do have some search data...
if(PresidentsDataStore.baseParams.query!==null){searchquery = PresidentsDataStore.baseParams.query;}
if(PresidentsDataStore.baseParams.firstname!==null){searchfirstname = PresidentsDataStore.baseParams.firstname;}
if(PresidentsDataStore.baseParams.lastname!==null){searchlastname = PresidentsDataStore.baseParams.lastname;}
if(PresidentsDataStore.baseParams.party!==null){searchparty = PresidentsDataStore.baseParams.party;}
if(PresidentsDataStore.baseParams.enteringoffice!==null){searchenteringoffice = PresidentsDataStore.baseParams.enteringoffice;}
if(PresidentsDataStore.baseParams.leavingoffice!==null){searchleavingoffice = PresidentsDataStore.baseParams.leavingoffice;}

Ext.Ajax.request({
waitMsg: 'Please Wait...',
url: 'database.php',
params: {
task: "PRINT",
// we have to send all of the search

query: searchquery, // if we are doing a quicksearch, use this
firstname : searchfirstname, // if we are doing advanced search, use this
lastname : searchlastname,
party : searchparty,
enteringoffice : searchenteringoffice,
leavingoffice : searchleavingoffice,
currentlisting: PresidentsDataStore.baseParams.task // this tells us if we are searching or not
},
success: function(response){
var result=eval(response.responseText);
switch(result){
case 1:
win = window.open('./presidentslist.html','presidentslist','height=400,width=600,resizable=1,scrollbars=1, menubar=1');
win.print();
break;
default:
Ext.MessageBox.alert('Uh hu...','Unable to print the grid!');
break;
}
},
failure: function(response){
var result=response.responseText;
Ext.MessageBox.alert('error','could not connect to the database. retry later');
}
});
}


Ок, вы можете удивится почему мы должны передавать так много параметров... Дело в том что... мы хотим распечатать всю нашу таблицу а наш DataStore содержит лишь 15 записей. Поэтому наш PHP файл собирается сделать запросы заново еще раз. не ограничивая поиск частичными запросами. Затем наш database.php сложит все это в файл listpresidents.html.

Вот наш database.php файл (сначала выбор)
    case "PRINT":
printPresidents();
break;


А затем функция печати:
function printPresidents()
{
// Ok since we limited our queries to 15 entries, we need to do a query again and get everything.
if($_POST['currentlisting']=='LISTING'){ // we are doing a basic listing or using the quicksearch
$query = "SELECT * FROM presidents pr, parties pa WHERE pr.IDparty = pa.IDparty";
// Here we check if we have a query parameter :
if (isset($_POST['query']) && ($_POST['query'] != "")){
$query .= " AND (pr.firstname LIKE '%".$_POST['query']."%' OR pr.lastname LIKE '%".$_POST['query']."%')";
}
$query .= " ORDER BY tookoffice";
$result = mysql_query($query);
$nbrows = mysql_num_rows($result);
} else if($_POST['currentlisting']=='SEARCH'){
$query = "SELECT * FROM presidents pr, parties pa WHERE pr.IDparty = pa.IDparty";
$firstname = $_POST['firstname'];
$lastname = $_POST['lastname'];
$enteringoffice = $_POST['enteringoffice'];
$leavingoffice = $_POST['leavingoffice'];
$party = $_POST['party'];

if($firstname != ''){
$query .= " AND firstname LIKE '%".$firstname."%'";
};
if($lastname != ''){
$query .= " AND lastname LIKE '%".$lastname."%'";
};
if($party != ''){
$query .= " AND pr.IDparty = '".$party."'";
};
if ($enteringoffice) {
$query .= " AND tookoffice >= '".$enteringoffice."'";
};
if ($leavingoffice) {
$query .= " AND leftoffice <= '".$leavingoffice."'";
};
$result = mysql_query($query);
$nbrows = mysql_num_rows($result);
}

// We now have our array, let's build our HTML file :
$file = fopen("presidentslist.html",'w');
fwrite($file, "<!DOCTYPE html PUBLIC '-//W3C//DTD XHTML 1.0 Transitional//EN' 'http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd'><html xmlns='http://www.w3.org/1999/xhtml'><head><meta http-equiv='Content-Type' content='text/html; charset=iso-8859-1' /><title>Printing the Grid</title><link rel='stylesheet' type='text/css' href='printstyle.css'/></head>");
fwrite($file, "<body><table summary='Presidents List'><caption>The Presidents of the United States</caption><thead><tr><th scope='col'>First Name</th><th scope='col'>Last Name</th><th scope='col'>Party</th><th scope='col'>Entering Office</th><th scope='col'>Leaving Office</th><th scope='col'>Income</th></tr></thead><tfoot><tr><th scope='row'>Total</th><td colspan='4'>");
fwrite($file, $nbrows);
fwrite($file, " presidents</td></tr></tfoot><tbody>");
for($i = 0; $i< $nbrows; $i++){
$data = mysql_fetch_array($result);
fwrite($file,'<tr');
if($i%1==0){
fwrite($file," class='odd'");
}
fwrite($file, "><th scope='row' id='r97'>");
fwrite($file, $data['firstname']);
fwrite($file,"</th><td>");
fwrite($file, $data['lastname']);
fwrite($file, "</td><td>");
fwrite($file, $data['name']);
fwrite($file, "</td><td>");
fwrite($file, codeDate($data['tookoffice']));
fwrite($file, "</td><td>");
fwrite($file, codeDate($data['leftoffice']));
fwrite($file, "</td><td> $");
fwrite($file, $data['income']);
fwrite($file, "</td></tr>");
}
fwrite($file, "</tbody></table></body></html>");
fclose($file);
echo '1'; // we are done.

}


На самом деле это очень просто. Мы просто вставляем запросы без ограничения количества записей и сохраняет полученный массив в HTML файл. Затем мы возвращаем 1.
Как будут выглядеть результаты на самом деле зависит от вас!
Некоторые предпочитают решения на основе экспорта в PDF формат. Вы можете найти эту информацию в топиках форумов.

Что запомнить:
Этот способ нельзя применить везде
Он не показывает колонки в нужном выбранном порядке и видимости
Это не самое лучшее решение.

Файлы этой части можно скачать здесь http://nicolas.bize.free.fr/ext/tutorial/Tutorial%20Part%2011.zip

Комментариев нет:

Отправить комментарий