I was making PDF from my webpage, but there are few styling which i am unable to load, like display: flex.
So for troubleshoot and go with other approach i decided to fetch first html from views.
my PDF were loading html from view with following code.
my view url is: https://digital.xtrazcon.com/reports/17
$report = Report::where('id', '=', $id)->firstOrFail();
$pdf = PDF::loadView('reports.container', ['view' => 'show', 'report' => $report, 'pdf_view' => 'yes'])->save($report_path);
so for calling rendered html, i tried following codes; but on all i am getting error.
all code after die are actually my tries.
$html = view('reports.container', compact(['view' => 'show', 'report' => $id])->render();
die(var_dump($html));
Says: compact(): Undefined variable $show
$html = view('reports.container', compact(['view' => 'show', 'report' => $report])->render();
die(var_dump($html));
Says: compact(): Undefined variable $show
Following one loads fine, but on view it gives error of missing data in the view which is 17
$html = view('reports.container', compact('report'))->render();
die(var_dump($html));
Says: Undefined variable $view (View: /var/www/vhosts/digital.xtrazcon.com/httpdocs/resources/views/reports/container.blade.php)
Line of code, which gives the above error is below
<?php echo $__env->make('reports.' . $view, \Illuminate\Support\Arr::except(get_defined_vars(), ['__data', '__path']))->render(); ?>
Please help, how can i call rendered html, so i can fix it for PDF.
Update Made
I tried something similar advise here, Laravel Meaning of Load View function
I have my view path at
/httpdocs/resources/views/reports/show.blade.php
so i decided to use
reports/show as a view
I tried following updated code then
$report = Report::where('id', '=', $id);
$html = view('reports/show', compact('report'));
dd($html->render());
die();
But still getting following error
Property [host] does not exist on the Eloquent builder instance. (View: /var/www/vhosts/digital.xtrazcon.com/httpdocs/resources/views/reports/show.blade.php)
I got that, the previous explanation mentioned at following query is similar and helpful to understand the direction.
Laravel Meaning of Load View function
i was just missing firstOrFail()
so i added this line, to call report first.
$report = Report::where('id', '=', $id)->firstOrFail();
then i call view in a following way, by adding my parameter in an array.
$html = view('reports/show',['report'=>$report]);
dd($html->render());
If i want to use compact, i tried following and works
$html = view('reports/show',compact('report'));
Related
I am using dompdf in my Laravel v8.26.1 app. I am also using Laravel Livewire v1.3.5.
I can get a view to download a pdf outside of Livewire, but can't seem to get it to work inside a Livewire view. I've tried every configuration I could think of, but keep running into road blocks. I am either getting an Undefined variable: workorder error, or no error at all, but also no download.
route
...
Route::livewire('/workorder/{workorder}/print', 'admin.workorders.printer')->name('admin.workorder.print')->layout('layouts.admin');
...
livewire/admin/workorders/print.blade
...
<div>
<button wire:click="generatePDF({{$workorder->id}})">Create PDF</button>
</div>
...
livewire/admin/workorders/printer.php
...
use Barryvdh\DomPDF\Facade as PDF;
...
public function generatePDF($id)
{
$record = Workorder::find($id);
$data = [
'project_id' => $record->project_id,
'project_name' => $record->project_name,
'customer_id' => $record->customer_id,
'generator_id' => $record->generator_id,
'workorder_po_number' => $record->workorder_po_number,
'workorder_number' => $record->workorder_number,
'prevailing_wage' => $record->prevailing_wage,
];
$pdf = PDF::loadView('livewire.admin.workorders.print', $data);
return $pdf->download('demo.pdf');
}
Here you go, just found this. fixed me right up. The only thing I had to change was in the $viewData variable, i just had to make it an array - ['viewData' => $viewData] and then i could access it in my view.
Here is the code in case that link ever goes down:
$pdfContent = PDF::loadView('view', $viewData)->output();
return response()->streamDownload(
fn () => print($pdfContent),
"filename.pdf"
);
I need to load a view into a view within CodeIgniter, but cant seem to get it to work.
I have a loop. I need to place that loop within multiple views (same data different pages). So I have the loop by itself, as a view, to receive the array from the controller and display the data.
But the issue is the array is not available to the second view, its empty
The second view loads fine, but the array $due_check_data is empty
SO, I've tried many things, but according to the docs I can do something like this:
Controller:
// gather data for view
$view_data = array(
'loop' => $this->load->view('checks/include/due_checks_table', $due_check_data, TRUE),
'check_cats' => $this->check_model->get_check_cats(),
'page_title' => 'Due Checks & Tests'
);
$this->load->view('checks/due_checks',$view_data);
But the array variable $due_check_data is empty
I'm just getting this error, saying the variable is empty?
Message: Undefined variable: due_check_data
You are passing the $view_data array to your view. Then, in your view, you can access only the variables contained in $view_data:
$loop
$check_cats
$page_title
There is no variable due_check_data in the view.
EDIT
The first view is contained in the variable $loop, so you can just print it in the second view (checks/due_checks):
echo $loop;
If you really want to have the $due_check_data array in the second view, why don't you simply pass it?
$view_data = array(
'loop' => $this->load->view('checks/include/due_checks_table', $due_check_data, TRUE),
'check_cats' => $this->check_model->get_check_cats(),
'page_title' => 'Due Checks & Tests',
'due_check_data' => $due_check_data
);
$this->load->view('checks/due_checks',$view_data);
Controller seems has no error. Check out some notices yourself:
<?=$due_check_data?>
This only available in PHP >= 5.4
<? echo $due_check_data; ?>
This only available when you enable short open tag in php.ini file but not recommended
You are missing <?php. Should be something like this
<?php echo $due_check_data; ?>
OK, i managed to solve this by declaring the variables globally, so they are available to all views.
// gather data for view
$view_data = array(
'due_check_data' => $combined_checks,
'check_cats' => $this->check_model->get_check_cats(),
'page_title' => 'Due Checks & Tests'
);
$this->load->vars($view_data);
$this->load->view('checks/due_checks');
public function about(){
$tempPageID = Input::get('page_id');
$pageLayout = DB::table('tbl_page')->where('id',$tempPageID)->first();
$data = array(
'page' => $pageLayout
);
$layout = $pageLayout->page_layout;
$theme = Theme::uses('homepage')->layout('default',$data);
return $theme->of('layouts/'.$layout,$data)->render();
}
This my code in my HomeController that calls the page about. the thing is the first division of my page is only included in the layout 'default.blade.php' which is {{ Theme::partial('bannerForm') }}
I'm trying to make the content of the whole page dynamic but cant do it because I cant pass the $data to the bannerForm.blade.php the error is Undefined variable: page .
Does anyone encountered this problem? What can I do to make this work? My second plan is to put the whole bannerForm code in the layout 'default.blade.php' to make it simple but still the same error. Unlike the last line of code which works fine.
I am trying a small ajax application whereby I only want to return a hello world string from my controller action.
it is returning the Hello world but along with this, it is also returning my template file..
I tried to disable it the templating using the following code in the action of my controlelr
$this->_helper->layout()->disableLayout();
$this->_helper->viewRenderer->setNoRender( true );
but this returns me this error
SCREAM: Error suppression ignored for
( ! ) Notice: Undefined property: Survey\Controller\SurveyController::$_helper in C:\wamp\www\zend\module\Survey\src\Survey\Controller\SurveyController.php on line 55
SCREAM: Error suppression ignored for
( ! ) Fatal error: Call to a member function layout() on a non-object in C:\wamp\www\zend\module\Survey\src\Survey\Controller\SurveyController.php on line 55
Call Stack
How do I fix this ?
EDIT
I modifed the controller such that it looks like this
public function registerAction()
{
$result = new JsonModel(array(
'some_parameter' => 'some value',
'success'=>true,
));
return( $result );
}
Added strategies in the module..module.config in module appl directory
'strategies' => array(
'ViewJsonStrategy',
),
Still, in the ajax response I get the template being returned
Here's a solid example:
http://akrabat.com/zend-framework-2/returning-json-from-a-zf2-controller-action/
You should be using JsonMoodels to send back a Json Response.
i use this in my controller:
$view = new ViewModel(array('form'=>$my_form));
//disable layout if request by ajax
$view->setTerminal($request->isXmlHttpRequest());
$view->setTemplate('path/to/phtml');
return $view;
The user wanted to know how to get just the html back, not json as Andrews reply offers.
I also wanted the html returned so i could use it with jquery qtip plugin and this is how i did it.
I also had to make the page degrade gracefully in case javascript failed, e.g. the page output should render properly in the layout template.
/**
* Tourist Summary action
*
* #return ViewModel
*/
public function touristSummaryAction()
{
// Get the Id
$id = $this->params()->fromRoute('id', '');
// Get the data from somewhere
$data = array() ;
// Get the html from the phtml
$view = new ViewModel(
array(
'id' => $id ,
'data' => $data ,
)
);
//disable layout if request by ajax
$view->setTerminal($this->getRequest()->isXmlHttpRequest());
return $view;
}
The most simple way to send ajax requests and handle responses is the zf2 module WasabiLib https://github.com/WasabiLib/wasabilib_zf2_skeleton_application
You only need to add "ajax_element" to the class-attribute to the element which you want to cause the ajax request. It does not matter if it is a form submit or a link or a button. Visit the examples page http://www.wasabilib.org/application/pages/examples
If your application does a lot of ajax I recommend this module.
Take a look at this module. www.wasabilib.org
Seems that you it manages ajax very well.
If you do not have a application you can use the Wasabilib Skeleton https://github.com/WasabiLib/wasabilib_zf2_skeleton_application. It comes with all necessary assets in the right place.
If you already have an application you should clone the module: https://github.com/WasabiLib/wasabilib
Minimal requirements: jQuery, ZF2
Add the module to application.config.php.
Include the wasabilib.min.js after jquery in the head of your layout.phtml
How it works
in your .phtml-file you have a form like this:
<form id="simpleForm" class="ajax_element" action="simpleFormExample" method="POST">
<input type="text" name="written_text">
<input type="submit" value="try it">
</form>
Anywhere else in your phtml you can place an element where the response is shown.
In your Controller the following method:
public function simpleFormExampleAction(){
$postArray = $this->getRequest()->getPost();
$input = $postArray['written_text'];
$response = new Response(new InnerHtml("#element_simple_form","Server Response: ".$input));
return $this->getResponse()->setContent($response);
}
The form has a class "ajax_element" this will say the the library that the request will be done with an xmlhttp-request. It wont work if you do not give an id to the requesting element. So the form has the ID "simpleForm". The action is the "path/to/controller" just like a normal request.
In the controller action a new WasabiLib\Ajax\Response object is instanciated.
The InnerHtml class is for replace, prepend and append html or normal text to a selector.
In this case the selector is an ID "element_simple_form". The first parameter of the InnerHtml class is the selector. Make sure that you write #yourElementId or .yourClassSelector. For IDs an "#" and for class selectors "."
The second parameter is the Text you want to fill in this element.
The response object can handle a lot more responses which you can add with
$response->add($anotherResponseType);
A list of possible response types is here: http://www.wasabilib.org/application/pages/components
The module is build to handle ajax request an responses in a very simple way. Once you have understood the behavior you can handle almost every practical ajax need.
This works for me:
public function ajaxAction(){
$data = array(
'var1' => 'var1Value',
'var2' => 'var2Value',
);
$response = $this->getResponse();
$response->setStatusCode(200);
$response->setContent(json_encode($data));
$headers = $response->getHeaders();
$headers->addHeaderLine('Content-Type', 'application/json');
return $response;
}
Output:
{"var1":"var1Value","var2":"var2Value"}
I have a controller which I use for a login form. In the view, I have a {error} variable which I want to fill in by using the parser lib, when there is an error. I have a function index() in my controller, controlled by array $init which sets some base variables and the error message to '':
function index()
{
$init = array(
'base_url' => base_url(),
'title' => 'Login',
'error' => ''
);
$this->parser->parse('include/header', $init);
$this->parser->parse('login/index', $init);
$this->parser->parse('include/footer', $init);
}
At the end of my login script, I have the following:
if { // query successful }
else
{
$init['error'] = "fail";
$this->parser->parse('login/index', $init);
}
Now, of course this doesn't work. First of all, it only loads the index view, without header and footer, and it fails at setting the original $init['error'] to (in this case) "fail". I was trying to just call $this->index() with perhaps the array as argument, but I can't seem to figure out how I can pass a new $init['error'] which overrides the original one. Actually, while typing this, it seems to impossible to do what I want to do, as the original value will always override anything new.. since I declare it as nothing ('').
So, is there a way to get my error message in there, or not? And if so, how. If not, how would I go about getting my error message in the right spot? (my view: {error}. I've tried stuff with 'global' to bypass the variable scope but alas, this failed. Thanks a lot in advance.
$init musst be modified before generating your view.
To load your header and footer you can include the following command and the footer's equivalent into your view.
<?php $this->load->view('_header'); ?>
to display errors, you can as well use validation_errors()
if you are using the codeigniter form validation.
if you are using the datamapper orm for codeigniter you can write model validations, and if a query fails due to validation rule violation, you get a proper error message in the ->error property of your model.
Code for your model:
var $validation = array(
'user_name' => array(
'rules' => array('required', 'max_length' => 120),
'label' => 'Name'
)
);
You might try this:
function index() {
$init = array(
'base_url' => base_url(),
'title' => 'Login',
'error' => ''
);
$string = $this->parser->parse('include/header', $init, TRUE);
$string .= $this->parser->parse('login/index', $init, TRUE);
$string .= $this->parser->parse('include/footer', $init, TRUE);
$this->parser->parse_string(string);
}
In parse()you can pass TRUE (boolean) to the third parameter, when you want data returned instead of being sent (immediately) to the output class. By the other hand, the method parse_string works exactly like `parse(), only accepts a string as the first parameter in place of a view file, thus it works in conjunction.