Why message is not being added to flashMessanger? - php

I created pagination and wanted to add check if user want to access page, which is not exisits. For example, there are 10 pages and user wants to open 999 page. I wanted to add error message, which will show, that there are no 999 page.
I tried this (and this worked):
public function listAction() {
$page = // getting page
$pagginator = // setting paginator
// this part will add message to the flashMessanger
if($page > $paginator->count()) {
$message = 'There are no such page';
$this->flashMessenger()->addMessage($message);
return $this->redirect()->toRoute('zfcadmin/news');
}
return new ViewModel(array(
'news' => $paginator,
));
}
This is working code. This is code for list action. This action is executed, when I type in browser this: example.com/admin/news. If I will type example.com/admin/news/page-500 browser will be redirected to example.com/admin/news and there will be message There are no such page.
I wanted to add same in other parts of my site and I got problem in index action of same controller. This is index action:
public function indexAction() {
return new ViewModel(array(
'news' => $this->getItems(),
'categoryName' => null,
));
}
As you see, I call function getItems(). Code of this function:
private function getItems($categoryId = null) {
$page = // getting page
$paginator = // getting paginator
if($page > $paginator->count()) {
$message = 'There are no such page';
$this->flashMessenger()->addMessage($message);
if($categoryId) {
return $this->redirect()->toRoute('news/category', array('category' => $categoryId));
} else {
return $this->redirect()->toRoute('news');
}
}
return $paginator;
}
I tried this and I got this error:
Fatal error: Call to undefined method
Zend\Http\PhpEnvironment\Response::count() in
F:\Server\domains\zf2-skeleton\module\News\view\news\news\index.phtml
on line 32
I realized, that it is because I returning $this->redirect as result of getItems() function and it is assigned to view variable news.
I tried this then:
if($page > $paginator->count()) {
$message = 'There are no such page';
$this->flashMessenger()->addMessage($message);
if($categoryId) {
$this->redirect()->toRoute('news/category', array('category' => $categoryId));
} else {
$this->redirect()->toRoute('news');
}
}
I am not getting any errors, but I am not getting message, that page is bad too.
I think... I bet, nobody here doesn't want to know what I think :)
Help me with this problem, please.
How to make redirect + write message to flashMessanger (so I can output it later) correctly in my case?
Update
I understand, that it is possible to return array from function get items and handle it. One of element will show should zf2 do redirect or not, another will show category id, third will containt paginator by itself, but it is dirty solution (but possible :( ).

Related

can not publish any page in edit mode

Could you please tell me how to publish pages after clicking edit button (left top menu) mode in cocrete5 cms version 5.8.1.0 not using compose button?
I can't publish any page clicking edit button in top left corner, editing it and clicking edit button again.
Publish Changes Button is disabled and there is message:
"The field Page Thumbnail is required."
But I can publish using compose menu (next to edit in left top corner).
What's the cause of this problem? Is it concrete5 bug?
It looks like it allows to publish if I comment out lines in check for publishinh method. But I can't still understand the cause of issue and how to fix it.
class CheckIn extends BackendInterfacePageController
{
protected $viewPath = '/panels/page/check_in';
// we need this extra because this controller gets called by another page
// and that page needs to know how to submit it.
protected $controllerActionPath = '/ccm/system/panels/page/check_in';
public function canAccess()
{
return $this->permissions->canApprovePageVersions() || $this->permissions->canEditPageContents();
}
public function on_start()
{
parent::on_start();
if ($this->page) {
$v = CollectionVersion::get($this->page, "RECENT");
$this->set('publishDate', $v->getPublishDate());
$this->set('publishErrors', $this->checkForPublishing());
}
}
protected function checkForPublishing()
{
$c = $this->page;
// verify this page type has all the items necessary to be approved.
$e = Loader::helper('validation/error');
if ($c->isPageDraft()) {
if (!$c->getPageDraftTargetParentPageID()) {
$e->add(t('You haven\'t chosen where to publish this page.'));
}
}
$pagetype = $c->getPageTypeObject();
// if (is_object($pagetype)) {
// $validator = $pagetype->getPageTypeValidatorObject();
// $e->add($validator->validatePublishDraftRequest($c));
// }
if ($c->isPageDraft() && !$e->has()) {
$targetParentID = $c->getPageDraftTargetParentPageID();
if ($targetParentID) {
$tp = Page::getByID($targetParentID, 'ACTIVE');
$pp = new Permissions($tp);
if (!is_object($tp) || $tp->isError()) {
$e->add(t('Invalid target page.'));
} else {
if (!$pp->canAddSubCollection($pagetype)) {
$e->add(
t(
'You do not have permissions to add a page of this type in the selected location.'
)
);
}
}
}
}
return $e;
}
The error says it all? 'The field Page Thumbnail is required.' Did you actually add a thumbnail?
Basically you can't submit a form without filling in all the required fields.
Or did you and still got the error?
I could solve the issue overriding file:
<?php
namespace Application\Attribute\ImageFile;
use Loader;
use Core;
class Controller extends \Concrete\Attribute\ImageFile\Controller
{
public function validateValue()
{
$f = $this->getAttributeValue()->getValue();
if (is_object($f)) {
return true;
}
$e = Core::make('helper/validation/error');
$e->add(t('You must specify a valid file for %s', $this->attributeKey->getAttributeKeyDisplayName()));
return $e;
}
}

Issue with redirect() when using conditional to evaluate multiple form buttons

So I've built a small conditional to evaluate which button is pressed in my form (as there are 2). This works fine and fires off the correct method and writes the appropriate data to the DB, however my redirect is not working. It saves() to the DB and then simply stays on the page designated as the POST route.
I suspect the problem has something to do with my conditional and the use of $this.
Here is my check_submit method:
public function check_submit()
{
if(!is_null(Input::get('add_to_invoice'))){
$this->invoice_add_item();
} elseif(!is_null(Input::get('complete_invoice'))) {
$this->invoice_complete();
}
}
Here is one of the 2 methods which I am currently testing:
public function invoice_add_item()
{
$input = Request::all();
$invoice_items = new Expense;
$invoice_items->item_id = $input['item_id'];
$invoice_items->category_id = $input['category'];
$invoice_items->price = $input['price'];
$invoice_items->store_id = $input['store'];
if(Input::has('business_expense'))
{
$invoice_items->business_expense = 1;
}
else{
$invoice_items->business_expense = 0;
}
$invoice_items->save();
return redirect('/');
}
Perhaps there is a better way of handling this in my routes(web) file, but I'm not sure how to go about this.
You should add the return to the check_submit() method. Something like
public function check_submit()
{
if(!is_null(Input::get('add_to_invoice'))){
return $this->invoice_add_item();
} elseif(!is_null(Input::get('complete_invoice'))) {
return $this->invoice_complete();
}
}
Better yet, you should probably return a boolean on invoice_add_item() and based on that, redirect the user to the correct place (or with some session flash variable with an error message)

Laravel extend/include layout if variable == 0

Im using laravel 4.0 im tyring to display a layout only if a variable ==0 (just in case a user tries to navigate to the url instead of clicking through) (i know I can redirect instead of extending but this is undesirable for now)
I am trying to get the layout to only extend when the user navigates to the page manually, noajax is set to true if their is no ajax request being sent when it goes to the function, so if the user where to navigate to the url manually it will still display the page but extend the layout.
#if ($noajax==1)
#extends('layouts.master')
#endif
#section('content')
//controller
public function test($id,$model)
{
if (Request::ajax())
{
//$foreign_key and $model must be <> null
if ($id == null || $model == null) {
$this->render('../Errors/missing_arg', 'error');
return;
}
if($model=="ArtObj")
{
$partable = "art_objects";
$path='img/art-objects/';
}
$parid=$id;
$noajax=0;
$mediaimgs = Media::where('parent_id' , $id )->where('parent_table', $partable)->paginate(15);
$response = Response::Json($mediaimgs);
return View::make('/Admin/manageimage/manage_image',compact('parid','mediaimgs','model','path','noajax'));
}
else{
if($model=="ArtObj")
{
$partable = "art_objects";
$path='img/art-objects/';
}
$parid=$id;
$mediaimgs = Media::where('parent_id' , $id )->where('parent_table', $partable)->paginate(15);
$response = Response::Json($mediaimgs);
$noajax = 1;
return View::make('/Admin/manageimage/manage_image',compact('parid','mediaimgs','model','path','noajax'));
}
}
In this case you should use 2 views in controller.
In controller you should use:
if ($noajax) {
return View::make('noajax');
}
else {
return View::make('ajax');
}
In noajax view you can extend from any other view and if noajax and ajax have common code, you should put it in separate file and use #include in those both views to include common part of code.

Laravel 4: using controller to redirect page if post does not exist - tried but failed so far

I'm working with Laravel 4, I have a page that shows posts e.g. example.com/posts/1 shows the first post from the db.
What I want to do is redirect the page to the index if someone tries to go to a url that doesn't exist.
e.g. if there was no post number 6 then example.com/posts/6 should redirect to example.com/posts
Here is what I have, is it on track at all?
public function show($id)
{
$post = $this->post->findOrFail($id);
if($post != NULL)
{
return View::make('posts.show', compact('post'));
}
else
{
return Redirect::route('posts.index');
}
}
Any ideas? Thanks :)
Exactly as Rob explained, you will need to do the following:
At the top of your file:
use Illuminate\Database\Eloquent\ModelNotFoundException;
Then within your show($id) method:
try
{
$post = $this->post->findOrFail($id);
return View::make('posts.show', compact('post'));
}
catch(ModelNotFoundException $e)
{
return Redirect::route('posts.index');
}
The method findOrFail() will throw an Exception if the page is not found. So if you wrap a try { ... } catch() { ... } around it, you can return a view of a redirect.

creating back page links in Codeigniter

I have a page with URL http://arslan/admin/category/index/0/name/asc/10 in Codeigniter.
In this URL, the uri_segment start from 0. This (0) is the default search value, name and asc are the default sort field and order, and 10 is the pagination index.
Now if I move to an add page with URL (http://arslan/admin/category/add/)
similarly like above "add" is the current function.
Now if i want to go back through a link to back page... How can I divert the user back? I can't make the URL go back.
Can somebody help me please?
I am not sure if i understand the question correctly, if not please ignore my answer, but I think you want a link to "go back to previous page", similar to the back-button in a web browser.
If so you could use javascript to solve this by simply using this line:
Go back
I extend the session class by creating /application/libaries/MY_Session.php
class MY_Session extends CI_Session {
function __construct() {
parent::__construct();
$this->tracker();
}
function tracker() {
$this->CI->load->helper('url');
$tracker =& $this->userdata('_tracker');
if( !IS_AJAX ) {
$tracker[] = array(
'uri' => $this->CI->uri->uri_string(),
'ruri' => $this->CI->uri->ruri_string(),
'timestamp' => time()
);
}
$this->set_userdata( '_tracker', $tracker );
}
function last_page( $offset = 0, $key = 'uri' ) {
if( !( $history = $this->userdata('_tracker') ) ) {
return $this->config->item('base_url');
}
$history = array_reverse($history);
if( isset( $history[$offset][$key] ) ) {
return $history[$offset][$key];
} else {
return $this->config->item('base_url');
}
}
}
And then to retrieve the URL of the last page visited you call
$this->session->last_page();
And you can increase the offset and type of information returned etc too
$this->session->last_page(1); // page before last
$this->session->last_page(2); // 3 pages ago
The function doesn't add pages called using Ajax to the tracker but you can easily remove the if( !IS_AJAX ) bit to make it do so.
Edit:
If you run to the error Undefined constant IS_AJAX, assumed IS_AJAX
add the line below to /application/config/constants.php
define('IS_AJAX', isset($_SERVER['HTTP_X_REQUESTED_WITH']) && strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) == 'xmlhttprequest');
There are two ways to solve your problem: First you could place a link that is using the javascript back-function onclick, like this ...
go back
... or you always save the current full page url into a cookie and use that for generating the back link - a helper could look like this (not tested) ...
/**
* save url to cookie
*/
if(!function_exists('urlhistory_save'))
{
function urlhistory_save()
{
$CI =& get_instance();
$CI->load->library('session');
$array = array(
'oldUrl' = $CI->session->userdata('newurl'),
'newurl' = $CI->uri->uri_string()
);
$CI->session->set_userdata($array);
}
}
/**
* get old url from cookie
*/
if(!function_exists('urlhistory_get'))
{
function urlhistory_get()
{
$CI =& get_instance();
$CI->load->library('session');
return $CI->session->userdata('oldurl');
}
}
In your controller you would use urlhistory_save() to save the current URL and in the view youd could use urlhistory_get() to retreive the old address like this:
<a href="<?php echo base_url().urlhistory_get(); ?>go back</a>
The most simplest way to redirect to your previous page , try this it work for me
redirect($this->agent->referrer());
you need to import user_agent library too $this->load->library('user_agent');
You can create a Session to go to back page as:
$this->session->set_userdata('ses_back_jobs','controller
name'.array_pop(explode('controller name',$this->input->server('REQUEST_URI'),2))); //Back page
Then if u want to redirect to some page use it:
redirect($this->session->userdata('ses_back_jobs'));
or use it to the anchor.

Categories