call a function in themes in yii - php

I have a file in my yii first project. my project has a new theme with this path
first_proj\themes\project\views\layouts\main.php
and i want to call a function in it like below
<?php
if($is_project_manager){
?>
<div class="each-pop-el" style="cursor:pointer" ng-click="showAllMemberTask()">show tasks</div>
<?php } ?>
and have function in
first_proj\protected\controllers\project.php
this is
public function actionIsProjectmanager(){
$project_manager = false;
$crt = new CDbCriteria;
$crt->condition = 'user_id=:uid and role=1';
$crt->params = array('uid'=>Yii::app()->user->id);
$project_manager= projectMember::model()->findAll($crt);
// $model_result = MyModel::model()->test();
$this->render('the url to theme and main.php file', array('is_project_manager' => $project_manager));
}
how can i reach to that main.php file ? what i must write instead of
the url to theme and main.php file in my function ?

You set the controllers layout to the file. So it would look like this:
$this->layout = 'main';
Layouts must be rendered with a view file as well though.
$this->render('index', array('is_project_manager' => $project_manager));
Then place an index.php file in your views/project folder with the actions content.
This assumes you've setup your config to have the theme as project

First thing you need to know is: No need to pass layout file to the view. When you use render() function, yii automatically add layout to your view. Then, For specifying the layout, you need to use $this->layout = '//layouts/main in your action.

use this in your view
<?php
if($this->isProjectmanager){
?>
<div class="each-pop-el" style="cursor:pointer" ng-click="showAllMemberTask()">show tasks</div>
<?php } ?>
and create a helper function (not an action!) in your controller
public function IsProjectmanager(){
if ($someConditon) {
return true;
}
else {
return false;
}
}

Related

How to dynamically load css file for each action in a controller?

I have a controller named 'Student' with two actions called 'index' and 'add'.
I want to load different css files for each of the action. So far i have tried is, i have imported Html Helper, created object of it and called its css method. When i run it, it is not throwing any error, nor showing expected result. Means, it is not loading css file dynamically in my view.. How can i dynamically load css files in different views from Controller?
Code:-
<?php
App::import('Helper','Html');
class StudentController extends AppController
{
public function index()
{
// $current_controller = $this->params['controller'];
// echo $current_controller;
//$view=new View(new Controller($current_controller));
//$Html=new HtmlHelper($view);
$Html=new HtmlHelper(new View(null));
//$html=new HtmlHelper(new View());
$Html->css('cake.generics');
//echo ;
//$this->Html->css("cake.generics");
}
public function add()
{
// $current_controller = $this->params['controller'];
// echo $current_controller;
$html=new HtmlHelper(new View(null));
$html->css("mystyle.css");
}
}
You can do it in view file e.g
//in your View/Students/add.ctp
$this->Html->css('yourstyle', array('block' => 'yourStyle'));
//in your layout file
echo $this->fetch('yourStyle');
the same with js files
// in your view
$this->Html->script('yourjs', array('block' => 'yourJs'));
//in your layout file
echo $this->fetch('yourJs');
you can also create a global layout file in View > Element like default_assets.ctp
after that add this file in your default layout file like,default_layout.ctp in View > Layout folder
and after access this in your controller like
public function index(){
$this->layout = "default_layout";
}
I got it working in this way,
I have added "mycss" variable in controller, index action:-
$this->set('mycss','custom');
And accessed this mycss variable from layout file:-
if(isset($mycss)){
$this->Html->css("$mycss");
}
And it worked.

Autoload a view on every page with codeigniter

So I have my views split up basically between three (3) files:
-- Header file
$this->load->view('templates/header', $data);
-- Main Body file
$this->load->view('login_view', $data);
-- Footer file
$this->load->view('templates/footer', $data);
Now I just recently started building, but I've noticed it's really annoying to retype the header and footer on every controller to tell it to load. Is there a way to automatically load the header and footer view on every request?
I found an article long time ago, but i can't seem to find it now, basically the author, (which i forgot) override the showing of output. this method of output will access your views regarding the given controller/method and will try to search in your views directory automatically.
Use at your own risk
Application/core/MY_COntroller.php
----------------------------------------------------------------------------
class MY_Controller Extends CI_Controller
{
protected $layout_view = 'layouts/application'; // default
protected $content_view =''; //data
protected $view_data = array(); //data to be passed
public function __construct()
{
parent::__construct();
}
public function _output($output)
{
if($this->content_view !== FALSE && empty($this->content_view)) $this->content_view = $this->router->class . '/' . $this->router->method;
$yield = file_exists(APPPATH . 'views/' . $this->content_view . EXT) ? $this->load->view($this->content_view, $this->view_data, TRUE) : FALSE ;
if($this->layout_view)
{
$html = $this->load->view($this->layout_view, array('yield' => $yield), TRUE);
echo $html;
}
}
}
Application/views/layouts/layout.php
----------------------------------------------------------------------------
<html>
<head>
<title>master layout</title>
</head>
<body>
<!-- this variable yeild is important-->
<div><?=$yield;?></div>
</body>
</html>
This is what i use to create my template. Basically you need a directory structure as follows.
+Views
|+layouts
||-layout.php
the layout.php will serve as your master template
How to use?
extend the controller
class User Extends MY_Controller
{
public function create_user()
{
//code here
}
public function delete_user()
{
//use a different master template
$this->layout_view = 'second_master_layout';
}
public function show_user()
{
//pass the data to the view page
$this->view_data['users'] = $users_from_db;
}
}
Just create directory in your views and name it with the controller name i.e user then inside it add a file you named your method i.e create_user
So now your Directory structure would be
+Views
| +layouts
| |-layout.php
| |-second_master_layout.php
| +user
| |-create_user.php
Just Edit the code to give you a dynamic header or footer
Here is the simple example which i always do with my CI project.
Pass the body part as a $main variable on controller's function
function test(){
$data['main']='pages/about_us'; // this is the view file which you want to load
$data['something']='some data';// your other data which you may need on view
$this->load->view('index',$data);
}
now on the view load the $main variable
<html lang="en">
<head>
</head>
<body>
<div id="container">
<?php $this->load->view('includes/header');?>
<div id="body">
<?$this->load->view($main);?>
</div>
<?php $this->load->view('includes/footer');?>
</div>
</body>
</html>
In this way you can always use index.php for your all the functions just value of $main will be different.
Happy codeing
Using MY_Controller:
class MY_Controller extends CI_Controller {
public $template_dir;
public $header;
public $footer;
public function __construct() {
parent::__construct();
$template_dir = 'templates'; // your template directory
$header = 'header';
$footer = 'footer';
$this->template_dir = $template_dir;
$this->header = $header;
$this->footer = $footer;
}
function load_views ($main, $data = [], $include_temps = true) {
if ($include_temps = true) {
$this->load->view('$this->template_dir.'/'.$this->header);
$this->load->view($main);
$this->load->view('$this->template_dir.'/'.$this->footer);
} else {
$this->load->view($main);
}
}
}
Then load it like: $this->load_views('login_view', $data);
You can do with library.
Create a new library file called template.php and write a function called load_template. In that function, use above code.
public function load_template($view_file_name,$data_array=array()) {
$ci = &get_instatnce();
$ci->load->view("header");
$ci->load->view($view_file_name,$data_array);
$ci->> load->view("footer");
}
You have to load this library in autoload file in config folder. so you don't want to load in all controller.
You can call
$this->template->load_template("index",$data_array);
If you want to pass date to view file, then you can send via $data_array
There is an article on this topic on ellislab forums. Please take a look. It may help you.
http://ellislab.com/forums/viewthread/86991/
Alternative way: Load your header and footer views inside the concern body view file. This way you can have batter control over files you want to include in case you have multiple headers and footer files for different purposes. Sample code shown below.
<html lang="en">
<head>
</head>
<body>
<div id="container">
<?php $this->load->view('header');?>
<div id="body">
body
</div>
<?php $this->load->view('footer');?>
</div>
</body>
</html>

Zend Framework 2: Composing web page of several parts

I need to compose a web page of several view templates (the view template rendering page content and a view template rendering sidebar). In my layout.phtml, I have two variable placeholders: $content and $sidebar:
......
<?php echo $this->sidebar; ?>
......
<?php echo $this->content; ?>
......
In my controller's action, I pass the data to these view templates through the ViewModels chained in a tree:
public function indexAction() {
// Preparing my data
// $form = ...
// $menuItems =
// $activeItem =
// Create sidebar view model
$sidebarViewModel = new ViewModel(array('menuItems'=>$menuItems, 'activeItem'=>$activeItem));
// Add it as a child to layout view model
$this->layout()->addChild($sidebarViewModel, 'sidebar');
// Page content view model
$viewModel = new ViewModel(array('form'=>$form));
return $viewModel;
}
But, because I have the sidebar on every page, I will have to copy and paste this code for every action of every controller. Is there any recommended way of reusing the code that populates the ViewModel for sidebar?
One approach would be to achieve this with a controller plugin.
Assuming you have wired it up with appropriate config, and you're in the Application module.
In module/Application/src/Application/Controller/Plugin/AddSidebar.php:
namespace Application\Controller\Plugin;
use Zend\Mvc\Controller\Plugin\AbstractPlugin;
class addSidebar extends AbstractPlugin {
public function __invoke($menu, $active) {
// create new view model
$sidebarVM = new ViewModel(array(
'menuItems' => $menu,
'activeItem' => $active
));
// add it to the layout
$this->getController()->layout()->addChild($sidebarVM, 'sidebar');
}
}
Then in each of your controllers:
$this->addSidebar($menuItems, $activeItem);
Another (probably better) option would be to hook into the render MvcEvent and add the sidebar there. You'd have to work out how to generate $menuItems and $activeItem in that context however.

How to extend anchor() function to anchor_admin() in CodeIgniter?

I would like to create my own function called anchor_admin() based on anchor() function in CodeIgniter.
I was thinking like:
I have defined admin path in config.php file e.g. like this:
$config['base_url'] = '';
$config['base_url_admin'] = 'my-custom-admin-folder';
and then
I need somehow create a new anchor_admin() function that extends anchor() function.
so instead of typing:
<?php echo anchor('my-custom-admin-folder/gallery', 'Gallery', 'class="admin-link"'); ?>
I would type only:
<?php echo anchor_admin('gallery', 'Gallery', 'class="admin-link"'); ?>
But the output wold be always:
Gallery
Basically I only need to ad the config variable $this->config->item('base_url_admin') at the end of the url generated by the core anchor() function.
How to do that?
Which files do I nned to create and where to put?
I guess creating a helper is not the way to go.
Should I create a library or could it be put as a function within my MY_Controller file in core folder of my application that I already have created and I am using it to load some stuff already?
In CodeIgniter you can 'extend' helpers ('extend' being a catch all term in this case as they're not actually classes). This allows you to add your own helper functions that will be loaded with the standard ones (in your case, the URL Helper).
It's explained in the CodeIgniter docs here - http://ellislab.com/codeigniter/user-guide/general/helpers.html
In your case you would want to do the following:
1- Create the file MY_url_helper.php in application/helpers/
2- Create your anchor_admin() function as below:
function anchor_admin($uri = '', $title = '', $attributes = '') {
// Get the admin folder from your config
$CI =& get_instance();
$admin_folder = $CI->config->item('base_url_admin');
$title = (string) $title;
if ( ! is_array($uri)) {
// Add the admin folder on to the start of the uri string
$site_url = site_url($admin_folder.'/'.$uri);
} else {
// Add the admin folder on to the start of the uri array
array_unshift($uri, $admin_folder);
$site_url = site_url($uri);
}
if ($title == '') {
$title = $site_url;
}
if ($attributes != '') {
$attributes = _parse_attributes($attributes);
}
return '<a href="'.$site_url.'"'.$attributes.'>'.$title.'</a>';
}
3- Use the helper and function how you normally would:
$this->load->helper('url');
echo anchor_admin('controller/method/param', 'This is an Admin link', array('id' => 'admin_link'));
Hope that helps!

Rendering a Static Page in Yii that resides in the Current Theme's Views

Ok I have a controller class in Yii that I want to use a different view folder aside from using its default view folder.
The natural behavior is when a $this->render("<view file>"); you would use the following to navigate your view file in the project...
"//" navigates project default view folder
"/" navigates current theme view folder
or do not use anything to select a view automatically in the
controller's default view folder
but my problem is i'm not rendering a view file but a STATIC PAGE that resides in /pages folder of a certain view folder. The static page I want to navigate is a static page the resides in my current theme folder views but the default is the controller navigates the static page inside the /protected/view folder
I tried also this override to modify the controller's view folder. I put this code in my controller that I want to render static pages in a theme folder
public function init(){
$this->layout = "//layouts/script";
$this->viewPath = "/js";
}
but the problem is the viewPath is readOnly variable.
Now my question is how I can render static pages that resides in my current theme's view folders?
NOTE: please if you don't understand my question, please don't down vote. I'm open to change and explain my problem for you as possible as I can
When you're overriding the actions method in your SiteController, somehow, you need to change the CViewAction's basePath property. It defaults to pages, as the documentation says.
Could you try something like this?
public function actions()
{
return array(
'page'=>array(
'class'=>'CViewAction',
'basePath'=>'path/to/your/theme/folder'
),
);
}
create a helper class for yourself and declare this method (change filepaths and other stuff):
public static function renderInternal($_viewFile_, $_data_ = null, $_return_ = false) {
// we use special variable names here to avoid conflict when extracting data
if (is_array($_data_)) {
extract($_data_, EXTR_PREFIX_SAME, 'data');
} else {
$data = $_data_;
}
$viewsDir = '/protected/views/internals/';
if ($_return_) {
ob_start();
ob_implicit_flush(false);
require(getcwd() . $viewsDir . $_viewFile_ . '.php');
return ob_get_clean();
} else {
require(getcwd() . $viewsDir . $_viewFile_ . '.php');
}
}
Use it/call it:
MyHelperClass::renderInternal( 'myviewfile', array( /* YOUR DATA */ ), /* RETURN CONTENTS OR NOT */ )
NOTE: Change $viewsDir to your desired directory.
try this in your any site controller or any controller..
public function actions()
{
return array(
'page'=>array(
'class'=>'CViewAction',
),
);
}
or refer this link...
http://www.yiiframework.com/wiki/22/how-to-display-static-pages-in-yii/

Categories