Using Codeigniter 4 I am creating pagination but it returns rendered HTML when i try
<?= $pager->makeLinks($page, $perPage, $total) ?>
How can I get JSON data instead of this HTML
makeLink function returns the HTML markup. To return the JSON object you have to use $pager->getDetails(). This function returns the array which can be converted into JSON as follows
return json_encode(['pager' => $pager->getDetails()]);
This simply converts the array into a JSON object which you can handle using JavaScript. You can also use Response object to convert it into JSON as follow :
$this->response->setContentType('application/json')->setJSON(['pager' => $pager->getDetails()])->send();
Look at my code:
$parpage=10;
$page=1;
$offset=0;
$this->model->where('id', $id)->paginate($perpage'default',$page,$offset);
On your controller call the pager library & the model
Create an array for passing the data on the view like the code below:
public function samplePager() {
$yourModel = new modelName();
$pager = \Config\Services::pager();
$data = [
'users' => $yourModel->paginate(10),
'pager' => $yourModel->pager,
];
return view('users/index', $data);
}
On your view file sample users/index.php you must put this after the foreach() loop on the page
<?php foreach($users as $user): ?>
<?php endforeach; ?>
<?= $pager->links() ?>
Related
I am developing an application using CakePHP 2.6 and having issues with passing a string containing url characters as a parameter through to a controller method.
In my view I have a chunk of code which echoes out a series of table rows containing data and passes through the page id, unit id and the id of the link which can sometimes contain a url.
<?php foreach($linklist as $l) { ?>
<tr id="Link_<?php echo $l['ID']; ?>">
<td><?php echo $l['Title']; ?></td>
<td class="buttontd"><?php echo $this->Form->postlink('Delete', array('action' => 'deletelink', $this->request->params['pass'][0], $results[0]['PageUnitTypeID'], $l['ID']), array('class' => 'button delete')); ?></td>
</tr>
<?php } ?>
When the postlink button passes the information over to the 'deletelink' action in the controller the url looks like this:
http://mydomainname.com/webpages/deletelink/239/7/urlhttp%3A%2F%2Fwww.google.co.uk%2F
Which shows that the url has been passed as the string but then in the action when I try to just var_dump() the third parameter it returns a string of www.google.co.uk and nothing more which is preventing me from doing a substr() call on the parameter to check if the first 3 characters are equal to url or not.
I have tried to wrap the parameter in the postlink call inside serialize() and urlencode() but neither has had the desired effect of returning the full string as
urlhttp%3A%2F%2Fwww.google.co.uk%2F
Does anyone know of a successful way to pass through a parameter like this without losing important characters?
Update 1: Deletelink action
public function deletelink($pid = null, $uid = null, $lid = null) {
$this->autoRender = false;
if (!is_null($pid) && is_numeric($pid) && !is_null($uid) && is_numeric($uid)) {
if (!is_null($lid)) {
if (substr($lid, 0, 3) == 'url') {
echo substr($lid, 0, 3);
} else {
echo substr($lid, 0, 3);
}
} else {
$this->Session->setFlash('It is unknown which link you wish to delete from the webpage', 'flash_message_bar', array('class' => 'error'));
return $this->redirect(array('action' => 'edit', $pid));
}
} else {
$this->Session->setFlash('It is unknown which on which webpage you wish to delete a link', 'flash_message_bar', array('class' => 'error'));
return $this->redirect(array('action' => 'index'));
}
}
CakePHP (or mod_rewrite I would say) is getting confused with the way your URL is formed.
Your safest option is to base64_encode the url parameter in the view, which will result in call similar to:
http://mydomainname.com/webpages/deletelink/239/7/dXJsaHR0cDovL3d3dy5nb29nbGUuY28udWsv
and base64_decode it later in the action, which will transform
dXJsaHR0cDovL3d3dy5nb29nbGUuY28udWsv
into
urlhttp://www.google.co.uk/
How to disable particular layout(example:menus.phtml) for particular pages in controller in ZF2?? In the below example menus.phtml should be disable for specific pages. Remaining pages must contain menus.phtml like header and footer.
<div>
header.phtml
</div>
<div>
menus.phtml
</div>
<div>
<?php echo $this->content; ?>
</div>
<div>
footer.phtml
</div>
There are various aproaches to this. Also modules.zendframework has quite a few modules here that may help you out.
If you are still keen on writing that yourself you could add variables to your layout within your controllers like so:
<?php
//YourController.php
public function someAction()
{
...
$this->layout()->footer = 'default';
...
}
//layout.phtml
<?php if ($this->footer === 'default') : ?>
//show the footer
<?php endif; ?>
Doing this is pretty inefficient though. Just imagine you'd need to do this to every action in all the controllers... I sure would not like to do that.
Now zf2 has a service and event layer that could help us out quite a bit here. This is a pretty nice read and introduction to it. You'd just write a service and trigger a event on your controllers/routes/whatever. Now you would also probably like to configure what is shown and what is hidden right? Thats pretty easy, too. Just write yourself a config file and merge it with the global.config like so:
<?php
//CustomModule/module.php
public function getConfig() {
$config = array();
$configFiles = array(
include __DIR__ . '/config/module.config.php',
include __DIR__ . '/config/module.customconfig.php',
);
foreach ($configFiles as $file) {
$config = \Zend\Stdlib\ArrayUtils::merge($config, $file);
}
return $config;
}
Source: Where to put custom settings in Zend Framework 2?
First, get the controller or action name:
$controllerName =$this->params('controller');
$actionName = $this->params('action');
then in your layout/view script add a simple logic.
<?php if ($actionName != 'action that you want to disable the layout/menu'): ?>
echo $this->render('menus.phtml');
<?php endif; ?>
I'm using the Post/Redirect/Get (PRG) pattern in my Laravel controllers to prevent duplicate form submission.
It works well when I don't use layouts or when my layouts don't use any variable. The problem is my layout uses a variable named $title. When I load the view and the layout without redirect it works well, the title set in the controller is passed to the layout, but after processing a form and redirecting to the same route which uses the same layout and the same controller method I get a "Undefined variable: title" error coming from my layout file.
Here is my code:
File: app/routes.php
Route::get('contact', array('as' => 'show.contact.form', 'uses' => 'HomeController#showContactForm'));
Route::post('contact', array('as' => 'send.contact.email', 'uses' => 'HomeController#sendContactEmail'));
File: app/controllers/HomeController.php
class HomeController extends BaseController {
protected $layout = 'layouts.master';
public function showContactForm()
{
$this->layout->title = 'Contact form';
$this->layout->content = View::make('contact-form');
}
public function sendContactEmail()
{
$rules = ['email' => 'required|email', 'message' => 'required'];
$input = Input::only(array_keys($rules));
$validator = Validator::make($input, $rules);
if($validator->fails())
return Redirect::back()->withInput($input)->withErrors($validator);
// Code to send email omitted as is not relevant
Redirect::back()->withSuccess('Message sent!');
}
}
File: app/views/layouts/master.blade.php
<!DOCTYPE html>
<html>
<head>
<title>{{{ $title }}}</title>
</head>
<body>
#yield('body')
</body>
</html>
File: app/views/contact-form.blade.php
#section('body')
#if (Session::has('success'))
<div class="success">{{ Session::get('success') }}</div>
#endif
{{
Form::open(['route' => 'send.contact.email']),
Form::email('email', null, ['placeholder' => 'E-mail']),
Form::textarea('message', null, ['placeholder' => 'Message']),
Form::submit(_('Send')),
Form::close()
}}
#stop
I don't understand why after redirecting the next line of code is ignored
$this->layout->title = 'Contact form';
I've tried with Redirect::action('HomeController#sendContactEmail'); or Redirect::route('show.contact.form'); but the result is the same.
The controller in charge of rendering that view is exactly the same before the redirect than after the redirect, and it has no business logic at all, so why it only works on the first case but not in the second?
This
Redirect::back()->withSuccess('Message sent!');
should be
return Redirect::back()->withSuccess('Message sent!');
When layout attribute is set in a controller and method is not returning any response, controller try to render the layout. In your sendContactEmail() method both conditions fulfilled and controller tried to render layout before $title is set.
see callAction() in Illuminate\Routing\Controllers\controller.
http://laravel.com/api/source-class-Illuminate.Routing.Controllers.Controller.html#93-127
Have you tried using
return View::make('contact-form', array('title' => 'Contact Form'));
Instead of interacting with the layout directly?
Redirect::back() creates a 302 using the referer value of the current HTTP request. I would start by comparing the initial form request to the redirect request to see if that yields any clues. You could also try...
Redirect::route('HomeController#showContactForm')->withInput()...
I know it's less dynamic but it will generate the URL rather then rely on the referer value in the HTTP header.
I am trying to echo a request in the view file in Kohana using Request::factory() method and i am sending a value in that request which i am unable to get in the User Controller here is my code:
The View file:
<h1> Welcome to My First View File </h1>
<?php echo Request::factory("user",array("id" => 123))->execute(); ?>
Then the User.php Controller have this code:
<?php defined('SYSPATH') or die('No direct script access.');
class Controller_User extends Controller {
public function action_index()
{
$value = $this->request->param('id');
$content = View::factory('menu')->bind("id", $value);
$this->response->body($content);
}
} // End User
and the view menu.php have this code:
<h2> This is the view called by Request and Parameters send was:
<?php echo $id; ?>
</h2>
when i run the code it display the text This is the view called by Request and Parameters send was: but it doesn't display the $id anyone can tell me why?
P.S: sorry for my bad English as its not my native language
Here you can see, that Request::factory() requires URI value a the first param. So, you should call something like:
<h1> Welcome to My First View File </h1>
<?php echo Request::factory(Route::get("user")->uri(array("id" => 123)))->execute(); ?>
or
<h1> Welcome to My First View File </h1>
<?php echo Request::factory("user/123")->execute(); ?>
First example uses reverse routing, where "user" is a Route name. I assume that you already have Route for handling URIs like '/user/123'.
the code i put in the mytheme template.php
function mytheme_theme(){
return array(
'mytheme_example' => 'example',
'argument' => array('myvar' => null),
);
}
the code i put in the node.tpl.php
<?php
$html = "";
$myvar = "hello,world";
$html .= theme('mytheme_example', myvar);
return $html;
?>
the code i put into the example.tpl.php
<div>
here is the <b><?php print myvar; ?></b>being created.
</div>
i have cleared the cache,but on the node article's page, there is no any output about hello world.
ps:which files i can use the hook_theme, template.php, module file. are there any files i can use this hook?
It looks like you have declared your hook_theme correctly in template.php so I do not think this is the issue.
I did spot a syntax issue with your node.tpl.php, should it not be:
<?php
$vars = array('myvar' => 'hello, world');
$html = theme('mytheme_example', $vars);
return $html;
?>
Note the associate array, with the 'myvar' (the variable declared in hook_theme), is being passed in as the key.
Another point, it is standard practice to name the template file the same as the hook name, so I would suggest calling the template mytheme-example.tpl.php.
See drupal.org for more information
I don't know if you have solved that issue yet.
I would try to declare my theme this way:
function mytheme_theme(){
return array(
'mytheme_example' => array(
'arguments' => array('arguments'=>array()),
'template' => 'example',
),
}
That's how I usually do and it works fine on me.