Include view page based on its route Zend2 Framework - php

How to include a page based on its route. Example of route: page_to_be_included
Page should be included like this in view:
<?php
if (...){
include 'page_to_be_included';
}
else {
show something else
}
?>
How can i include one view in another view?

In most cases each route should lead to its own action, then each action can set its on view (or just use default).
If more then one route lead to the same action, you can check the route in the controller and set the view according:
if ( $this->getEvent()->getRouteMatch()->getMatchedRouteName() == 'the_route_name' ) {
$viewModel = new ViewModel();
$view->setTemplate('what/ever/page');
return $viewModel->setVariables(array('var2pass'=>'hi'));
}

Maybe you means to include a view script (of an other controller)?
$viewmodel = new ViewModel();
$page = $this->forward()->dispatch('thecontroller', array(
'action' => 'youractionname',
));
$viewmodel->addChild($page, 'page');

I think you mean you want to put partial into you view. If you want to do this just use partia() view helper in your view with specified string path to your partial.
Lets say you have folder structure of your Test module like this: module\Test\view\partial\name-of-partial.phtml
$this->partial('partials/name-of-partial');

Related

Laravel single route point to different controller depending on slugs

I'm new to laravel and I have searched a lot for an answer to my problem but either it's not applicable or I'm not getting it.
I have a FileMaker solution for a client that handle customers and events. Each customer to my client have their own event websites that is managed via the solution. A cms simply. Each customer get a site with a url like clientsite.com/event.
Each page in the event has a page-type and I would like to address different controllers depending on the type.
In routes.php i have:
Route::group(['middleware' => ['sal', 'menu']], function () {
Route::get('/{event}/{page}', function($event, $page) {
// Query page for page-type and use controller depending on type
});
});
There are many page types (standard text/image, specialized forms etc) and therefor I would like to address different controllers.
Event names are always unique but pages are not.
You could call a controller manually inside the route closure. Though I would suggest doing the validation in a helper file to make the route file clean and readable.
Route::group(['middleware' => ['sal', 'menu']], function () {
Route::get('/{event}/{page}', function($event, $page) {
// you could do something like
$user_type = Auth::user()->user_type;
if($user_type == "organizer")
{
$controller = $app->make('OrganizerController');
return $controller->callAction('controllerFunc', $parameters = array());
}
else
{
$controller = $app->make('ClientController');
return $controller->callAction('controllerFunc', $parameters = array());
}
});
});
An alternative to the route solution could be to handle the logic in the controller itself:
First, update routes.php to something like:
Route::group(['middleware' => ['sal', 'menu']], function () {
Route::get('/{event}/{page}', 'RoutesController#index');
});
Then, in the RoutesController.php file (add to app/Http/Controllers), you can do something similar to:
public function index()
{
$event = Request::segment(1); // get the {event} part of the route
$page = Request::segment(2); // get the {page} part of the route
// get event data from database, e.g.
$event_data = Event::where( 'slug', $event )->first();
// load correct page
switch ( $page ) {
case "people":
return $this->people();
break;
case "anotherPage":
return $this->another_page();
break;
}
}
private function people()
{
// show view
return View::make('event.people');
}
This solution keeps your routes file clean, but also lets you handle the different event and page data, and load different views depending on the page being looked at. Your extra logic would be better in a controller rather than the routes file.
It all depends on where you prefer to code your page / view logic. You can use this approach call functions in the same controller, or external ones.

Passing a url value to view thru routes

I have a url this http://localhost/laravel/public/page/sign-up now..
I want to get the value of the url which is "sign-up" in the view..
Its not including the sign-up view.. I'm just new in laravel..
and before I posted here, I have done my research and found nothing relevant
in my master.blade.php I am using this
If anybody could enlighten me what is going on here and what is lacking.. I would really appreciate it
View
#if ($page == 'sign-up')
#include('pages/unregistred/sign-up')
#endif
Routes:
Route::get('page/{action}', function($action){
return View::make('layouts.master')->with('page', $action);
});
You can use Named routes:
Route::get('page/{action}', ['as' => 'sign-up', function($action){
return View::make('layouts.master')->with('page', $action);
}]);
And in the layout use:
#if (Route::currentRouteNamed('sign-up'))
#include('pages/unregistred/sign-up')
#endif
Also you can use Route::is() method for matching:
#if (Request::is('page/sign-up'))
Another way if the prefix of the page is /page/:
Request::segment(2); // return "sign-up"
Other info are in the docs: Request Information
I suggest you to use the route to show the correct view and not include them in the layout using conditions.
You can find a guide to the layout here: Blade templating
Try something like this:
Route:
Route::get('page/{type}', 'PageController#index');
Controller:
class PageController extends BaseController {
public function index($type)
{
return View::make('page.register', array('page' => $type));
}
}

Render a different page based on login using yii framework

I would like the home page rendered depend on the user role login.
Currently I have this in the protected/controllers/break;SiteController.php but it redirects to another page.
protected function roleBasedHomePage() {
$roles = Yii::app()->user->getState('roles'); //however you define your role, have the value output to this variable
switch($role) {
case 'admin':
$this->redirect(Yii::app()->createUrl('site/page',array('view'=>$roles.'homepage')));
break;
case 'b':
$this->redirect(Yii::app()->createUrl('site/page',array('view'=>$roles.'homepage')));
break;
case 'guest':
$this->redirect(Yii::app()->createUrl('site/page',array('view'=>'homepage')));
break;
//etc..
}
public function actionLogin()
{
$model = new LoginForm();
if (isset($_POST['ajax']) && $_POST['ajax'] === 'login-form') {
echo CActiveForm::validate($model, array('username', 'password', 'verify_code'));
Yii::app()->end();
}
if (isset($_POST['LoginForm'])) {
$model->attributes = $_POST['LoginForm'];
if ($model->validate(array('username', 'password', 'verify_code')) && $model->login()) {
Yii::app()->user->setFlash('success', 'Welcome ' . app()->user->name);
// $this->redirect(Yii::app()->user->returnUrl);
$this->roleBasedHomePage();
}
}
$this->render('login', array('model' => $model));
}
}
This works if I want to redirect the page but I want the home page url to be the same and the content to change depending on 'roles'.
e.g. if the user is 'admin' then I want 'adminhome' rendered
I'm guessing the function below has something to do with it?
public function actionIndex()
{
$this->render('index');
}
you can do this easily. first create a view for every role. then redirect every one to your home page after login, but check their role and depending on that, "renderPartial()" the view for that role. like:
switch($role){
case 'admin' :
$this->renderPartial('application.views.site._admin'); // view for admin
break;
case 'superUser':
$this->renderPartial('application.views.site._superUser');// view for super user
break;
I would use Ajax as an option, if what you want to change is the content of the page but keep the same footer and header.
For instance:
1- Create three different views, admin.php, b.php and guest.php.
2- In your controller create three different methods: renderAdmin(), renderB() and renderGuest(). Each one will render the corresponding view.
3- In the same controller define the Access rules for the specific role and methods, so an Ajax call from an invalid user will not be allowed (in case someone sees your code and tries to invoke the method based in the Ajax URL where you send the post to). This because in the default header that you use in your 'index.php' you will assign the JS script which calls the specific method, the method will return the view and thats what you render on the 'main' content div.
4- In the login() you call the index method.
5- In the index method you render the 'index' view and pass the path to the specific JS script which calls the 'adminview', for instance.
You could also use Update content in AJAX with renderPartial
HTH
Change your index action in the controller to something like this:
public function actionIndex()
{
$roles = Yii::app()->user->getState('roles');
$view = $this->getViewForRole($roles); // you have to implement this function
$this->render($view . '_index');
}
Create the view files in the views folder: admin_index.php, customer_index.php etc.

How to structure a dynamic website with Codeigniter

I have some experience with php, but I just recently started learning Codeigniter. I used to have a website with a fixed navigation pane and sidebar, but the main section of the site loaded dynamically based on a Get variable. It was basically
include head.php
include navbar.php
include sidebar.php
include the page requested from the get variable (home, about, contact, etc.)
include footer.php
I liked this because the entire site did not have to reload when the user navigated from page to page.
I can't figure out how do this with Codeiginiter. Should I be using a controller for each page or one controller with a function for each page? Do anyone know of a good tutorial that does something similar? All the tutorials I've seen reload the entire site for every page.
Edit: Essentially I want to do this but with Codeigniter
Since it looks like you want relatively static content, but loaded dynamically you can do with one controller and (maybe) one method in the controller.
To do it with one method, do this in the welcome controller:
public page( $page_id ){
// views/header.php
$this->load->view( "header" );
if( $page_id = "about" ){
$this->load->view("about"); // views/about.php
}
else if( $page_id = "contact" ){
$this->load->view("contact"); // views/contact.php
}
// views/footer.php
$this->load->view("footer");
}
This takes a single get variable and figures out what page to load in between the header and footer.
This way www.yoursite.com/page/about will load the about page, www.yoursite.com/page/contact will load the contact page
Now, if you want to get rid of the /page part, you need to do some URL rerouting in application/config/routes.php
Alternatively you could use several methods in one controller:
public about( ){
// views/header.php
$this->load->view( "header" );
$this->load->view( "about" );
// views/footer.php
$this->load->view("footer");
}
public contact( ){
// views/header.php
$this->load->view( "header" );
$this->load->view( "contact" );
// views/footer.php
$this->load->view("footer");
}
Now your URLs look nicer without routing, but you have to load the header/footer for every page.
do you really like to copy/paste many $this->load->view() to any controller function?
It's a spaghetti code. You can try next: for example we have main.php controller as default controller. This main controller contain main function:
public function index()
{
ob_start();
$this->load->model('mainmodel');
$data = $this->mainmodel->_build_blocks(); //return array with needed blocks (header, menu, content, footer) in correct order
foreach ($data->result_array() as $row) {
$this->load->module($row['block_name']);
$this->name = new $row['block_name'];
$this->name->index();
}
ob_end_flush();
}
So, each other controller also have index() function which can dispatch actions depends on url segments, prepare params etc.
Footer controller as example (I use Smarty as template engine):
public function index()
{
$this->mysmarty->assign('year', date("Y"));
$this->mysmarty->view('footer');
return true;
}
Content controller will have:
public function index()
{
$name = $this->uri->segment(1, 'index');
$act = $this->uri->segment(2, 'index');
$this->load->module($name);
$this->name = new $name;
$pageData = $this->name->_show($act);
if ($pageData)
{
$this->mysmarty->assign($name, $pageData);
}
$this->mysmarty->view($name);
}
Thats mean what if you want to show http://site.name/page/contactus , we do next:
1) main.php start cycle by needed blocks
2) firstly we show header.tpl by header controller
3) then we show menu
4) then we call content controller which parse url, found what he should call _show() function in Page controller and pass action='contactus' to it. _show() function can contain some switch/case construction which show templates depends of action name (contactus.tpl in this case)
5) in the end we show footer template
In such case we have flexible structure. All controllers should have index() functions and all controllers who can be called in content should have _show($act) function. Thats all.
In codeIgniter you can do that like this, you can load different views at the same time from your controller. for example:
for example in your navbar view you have a Contacts button in your menu that would look like this:
<a href='contacts'>Contacts</a>
In your controller:
public function contacts()
{
$this->load->view('header');
$this->load->view('navbar');
$this->load->view('sidebar');
$this->load->view('contacts_view');
$this->load->view('footer');
}
So we're assuming here that you have the following views already that is ready to be loaded (header.php, navbar.php, sidebar.php, contacts_view.php, footer.php).
UPDATE:
you don't need to have $_GET[] request, just provide the method name from your controller in the <a> anchor tag
in codeigniter i using template
first make template file in one folder with header.php, navbar.php, etc.
example : template.php
<?php
echo $this->load->view('header'); //load header
echo $this->load->view('navbar');//load navbar
echo $this->load->view('sidebar');//load sidebar
echo $this->load->view($body); //load dynamic content
echo $this->load->view('footer');//load footer
?>
second in controller
function index( ){
$data['body'] = 'home'; // cal your content
$this->load->view('template', $data);
}

Do Partial Views Need Separate Controllers if they Use Different Models?

I've created a series of partial views for a page in our Yii Framework site. Each partial view has it's own model because they call subsections of the main model class. Since each partial view has it's own model, do I need separate controller classes for each?
My loadModel portion of the User controller is as follows:
public function loadModel($id,$model_name='Users')
{
$model=Users::model()->findByPk($id);
if($model===null)
throw new CHttpException(404,'The requested page does not exist.');
return $model;
}
It is being called from this section of the User Controller:
public function actionProfile($id=''){
$user = Users::model()->find('username=:id', array
(':id' => Yii::app()->user->id));
if(!$id){
$id = $user->id;
if(!$id)
$this->redirect('login');
}
if( getUserSess('user_type') == 'Sitter') {
$this->render('profile_detail', array('user_id' => $id ));
} else {
$this->render('petowner_profile_detail',array(
'model'=>$this->loadModel($id),
));
}
}
I think I understand what you are trying to do. My answer would be no, you don't need separate controller actions for each partial view. I would create a view that then calls all the partial views. If you use gii to create your CRUD functionality you will see both the create and edit views call a partial view of the form. You would do this same thing only call multiple partial views in your view file. If you need different models just make sure your controller passes them to your main view file first so that it can then pass them on to the partial views. Hopefully that helps you out.
Here is the code if there is no relationship:
$partialUser = new PartialUser::model->findByAttributes(array('uid'=>$id)); //IF NOT UID PUT WHATEVER YOU HAVE THE COLUMN NAME
$this->render('petowner_profile_detail',array(
'model'=>$this->loadModel($id),
'partialUser' => $partialUser,
));
If you did have a relationship setup you could easily just do this:
$current_user = $this->loadModel($id);
$this->render('petowner_profile_detail',array(
'model'=> $current_user,
'partialUser' => $current_user->partialUser, //whatever you set the name of the relationship as in the model
));

Categories