Given an html/javascript 'widget' which needs to have certain fields customized before use. For example, the css class ids need to be unique as the widget may appear more than once on the same page.
Let's say I want to keep the markup (js/html) of the widget stored as a template so that I can fill in the values that need to be customized during resuse.
I know that Zend Framework's views give you at least part of this functionality, but each view is generally associated with a particular controller. Given that this widget could be created from any controller, yes still needs to be able to access some properties stored in a controller (or model). Where should I put the widget markup and how then do I fill in the custom values?
Can I create a custom view that can be reused within the same page (appear more than once) as well as on other pages? If so, how do I set that up?
Sounds like you need a ViewHelper http://framework.zend.com/manual/en/zend.view.helpers.html. Create a custom helper that will fetch the data from a model and just simply output it. This way it won't depend on any controller, can be called in either the layout or in any view script. Example:
// views/helpers/Widget.php
class Zend_View_Helper_Widget extends Zend_View_Helper_Abstract
{
protected $_model = null;
protected $_view = null;
public function widget()
{
$data = $this->_getDataFromModel();
return $this->_view->partial('widget.phtml', array('data' => $data));
}
public function setView(Zend_View_Interface $view)
{
if($this->_view === null) {
$this->_view = $view;
}
return $this->_view;
}
protected function _getDataFromModel()
{
$this->_model = $this->_getModel();
return $this->_model->getDataForWidget();
}
protected function _getModel()
{
if($this->_model === null) {
$this->_model = new Model_Widget(); // or whatever it's called
}
return $this->_model;
}
The partial script:
// views/scripts/widget.phtml
<div class="widget-class"><?php echo $this->data; ?></div>
And when you need it in your views just call it like <?php echo $this->widget(); ?>
Note that I'm rendering the widget in a separate partial view script, just to avoid having html/css in the helper itself.
Hope this helps to get you started :)
Zend_View_Helper_Partial
Example:
<?php echo $this->partial('partial.phtml', array(
'css_id' => 'foobar')); ?>
To run this from any other module:
<?php echo $this->partial('partial.phtml', 'partials_module', array(
'css_id' => 'foobar')); ?>
In your partial view script (partial.html) you would then have access to $this->css_id.
Related
How to add Custom button and its functionality in Admin Silverstripe?
Please tell me solution.
Custom Button add only in one menu.
Like #wmk mentioned in the comments, you can just take the framework code for GridFieldPrintButton as a base and go from there. SilverStripe also have a basic tutorial for creating a custom ActionProvider.
Rather than rehash the tutorial here, I will provide you a very basic custom action provider that you can copy and extend to do what you need. While you don't note the exact result you are wanting from the button, I will provide just a very generic class.
This code is a stripped down version of the GridFieldPrintButton that #wmk mentioned. It supports both the button itself invoking the custom code as well as the URL.
I've noted in the code a reference that I have kept to "grid-print-button", this is to make your button sit nicely next to the print rather than likely sitting on another line (as it did in my testing on an older 3.1 site I built).
class GridFieldCustomButton implements GridField_HTMLProvider, GridField_ActionProvider, GridField_URLHandler {
protected $targetFragment;
protected $someCustomConstructData;
//TargetFragment is just for positioning control of the HTML fragment
//SomeCustomConstructData is just an example of providing some default options into your butotn
public function __construct($targetFragment = "after", $someCustomConstructData = null) {
$this->targetFragment = $targetFragment;
$this->someCustomConstructData = $someCustomConstructData;
}
//Generate the HTML fragment for the GridField
public function getHTMLFragments($gridField) {
$button = new GridField_FormAction(
$gridField,
'custom',
'Custom Action',
'custom',
null
);
return array(
//Note: "grid-print-button" is used here to match the styling of the buttons in ModelAdmin
$this->targetFragment => '<p class="grid-print-button">' . $button->Field() . '</p>',
);
}
public function getActions($gridField) {
return array('myCustomAction');
}
public function handleAction(GridField $gridField, $actionName, $arguments, $data) {
if($actionName == 'myCustomAction') {
return $this->handleMyCustomAction();
}
}
//For accessing the custom action from the URL
public function getURLHandlers($gridField) {
return array(
'myCustomAction' => 'handleMyCustomAction',
);
}
//Handle the custom action, for both the action button and the URL
public function handleMyCustomAction($gridField, $request = null) {
//Do your stuff here!
}
}
Continuing on from the discussion in the comments, you will need to modify your custom ModelAdmin to add new components to its GridField.
class MyCustomAdmin extends ModelAdmin
{
private static $managed_models = array(
'MyCustomObject'
);
private static $url_segment = 'custom-admin';
private static $menu_title = 'All Custom Objects';
public function getEditForm($ID = null, $Fields = null)
{
$form = parent::getEditForm($ID, $Fields);
$fields = $form->Fields();
$gridField = $fields->fieldByName('MyCustomObject');
$gridFieldConfig = $gridField->getConfig();
$gridFieldConfig->addComponent(new GridFieldCustomButton());
return $form;
}
}
Specifically, the line $gridFieldConfig->addComponent(new GridFieldCustomButton()) does the work, taking your custom button as I have shown above and added it to the ModelAdmin. You can also specify where it should go in the GridField too by providing "buttons-before-left" as the first argument in the GridFieldCustomButton constructor.
eg. $gridFieldConfig->addComponent(new GridFieldCustomButton("buttons-before-left"))
More information regarding GridField fragments can be found in the SilverStripe developer documentation.
I use this partial to generate my submenu.
<?php foreach ($this->container as $page): ?>
<?php foreach ($page->getPages() as $child): ?>
<a href="<?php echo $child->getHref(); ?>" class="list-group-item">
<?php echo $this->translate($child->getLabel()); ?>
</a>
<?php endforeach; ?>
<?php endforeach; ?>
Which is called like this:
$this->navigation('navigation')->menu()->setPartial('partial/submenu')->render();
But when i render the menu the "$child->getHref()" renders the url without the needed "slug/id" parameter.
I tried to create the url with "$this->url()" in ZF1 you could pass the params in an array to the partial but in ZF2 that doesn't seem to work anymore.
Can anybody tell me how to add the params to the menu urls?
Thanks in advance!
PS!
I'm not referring to $this->Partial, i'm talking about $this->navigation('navigation')->menu()->setPartial('partial/submenu')->render() which apparently doesn't support a param array.
If I'm understanding your question, yes, you can pass params to partials. Example:
<?php echo $this->partial('partial.phtml', array(
'from' => 'Team Framework',
'subject' => 'view partials')); ?>
See http://framework.zend.com/manual/2.3/en/modules/zend.view.helpers.partial.html
I'm not sure this completely solves your issue, since you are not showing what the menu helper is. Is it your own view helper? Are you saying that setPartial method only accepts one argument?
All that said, have you considered Spiffy Navigation?
https://github.com/spiffyjr/spiffy-navigation
It's been sometime since this question was asked, however today I came across the same problem (using version 2.4).
If you have a segment route to be included within the menu that requires some parameters there is no way to pass these through to the navigation's view partial helper.
The change I've made allows a ViewModel instance to be passed to the menu navigation helper's setPartial() method. This view model will be the context for the navigation's partial template rendering; therefore we can use it to set the variables we need for the route creation and fetch them just like within other views using $this->variableName.
The change requires you to extend the Menu helper (or which ever navigation helper requires it).
namespace Foo\Navigation;
use Zend\Navigation\AbstractContainer;
use Zend\View\Model\ViewModel;
class Menu extends \Zend\View\Helper\Navigation\Menu
{
public function renderPartial($container = null, $partial = null)
{
if (null == $container) {
$container = $this->getContainer();
}
if ($container && $partial instanceof ViewModel) {
$partial->setVariable('container', $container);
}
return parent::renderPartial($container, $partial);
}
public function setPartial($partial)
{
if ($partial instanceof ViewModel) {
$this->partial = $partial;
} else {
parent::setPartial($partial);
}
return $this;
}
}
Because this extends the default implementation of the helper updated configuration is required in module.config.php to ensure the extend class is loaded.
'navigation_helpers' => [
'invokables' => [
'Menu' => 'Foo\Navigation\Menu',
],
],
The menu helper will then accept a view model instance.
$viewModel = new \Zend\View\Model\ViewModel;
$viewModel->setTemplate('path/to/partial/template')
->setVariable('id', $foo->getId());
echo $this->navigation()
->menu()
->setPartial($viewModel)
->render();
The only change in the actual partial script will require you to create the URL's using the URL view helper.
foreach ($container as $page) {
//...
$href = $this->url($page->getRoute(), ['id' => $this->id]);
//...
}
Our Yii Framework application has the following defined as part of the UserProfileImages model:
public function getProfileImages($param, $user_id) {
if(isset($param['select']) && $param['select']=='all'){
$profile_images = UserProfileImages::model()->findAllByAttributes( array( 'user_id'=>$user_id) );
} else {
$profile_images = UserProfileImages::model()->findByAttributes( array( 'user_id'=>$user_id) );
}
return $profile_images;
}
How would I wire up the above snippet to a widget in my view to return all the images for a given user?
Bonus Question: Which image rotator do you suggest to render the above?
In your view file, add something like this, assuming that your controller specified $user_id:
$this->widget('UserProfileImagesWidget', array(
"userProfileImages" => UserProfileImages::getProfileImages(
array("select" => "all"),
$user_id
),
"user_id" => $user_id
));
Depending on your MVC philosophy, you could also retrieve the userProfileImages data in the controller and pass that data to your view.
Define a widget like this:
class UserProfileImagesWidget extends CWidget {
public $user_id;
public $userProfileImages = array();
public function run() {
$this->render("userProfileImage");
}
}
Finally, in the userProfileImages.php view file, you can do something like this:
if(!empty($this->userProfileImages)) {
// Your display magic
// You can access $this->user_id
}
As a side note: You might want to change the order of your parameters in getProfileImages. If $user_id is the first parameter, you can leave out $params completely in case you don't want to specify any.
I have two modules in my installation. Both modules' controllers pass a variable called
$data['content']
to their views. Also, the first module's view runs the second module via
<?php echo Modules::run('module2'); ?>
and after that is supposed to display values from its $data['content'] variable. Unfortunately, that's when the first module's $data content is substituted with the second module's $data. This is pretty inconvenient for me, so I would like to know if there is a way to "protect" the $content variables and keep them only within their associated modules?
I would like to avoid renaming $data['content'] if possible. I've found a not-so-perfect solution in using
$data(__CLASS__)
but I am curious if it is possible not to change $data['content'].
class Some extends MX_Controller{
public function __construct(){parent::__construct();}
public function index(){
$this->load->view('template', array( //Primary template
'content' => 'some_index' // index view
));
}
public function _module_1(){
$this->load->view('module_1_view', array( //Module View : NO primary template
'' => '' <= no need to load view here, only data
));
}
public function _module_2(){
$this->load->view('module_2_view', array( //Module View : NO primary template
'' => '' <= no need to load view here, only data
));
}
}
-
template.php
<html>
<?php $this->load->view($content); ?>
</html>
-
some_index.php
<html>
//call modules
<?php echo Modules::run('some/_module_1'); ?>
<?php echo Modules::run('some/_module_2'); ?>
//call module from another class
<?php echo Modules::run('another_class/_module_1'); ?>
</html>
What's the best way for constructing headers, and footers? Should you call it all from the controller, or include it from the view file? I'm using CodeIgniter, and I'm wanting to know what's the best practice for this. Loading all the included view files from the controller, like this?
class Page extends Controller {
function index()
{
$data['page_title'] = 'Your title';
$this->load->view('header');
$this->load->view('menu');
$this->load->view('content', $data);
$this->load->view('footer');
}
}
or calling the single view file, and calling the header and footer views from there:
//controller file
class Page extends Controller {
function index()
{
$data['page_title'] = 'Your title';
$this->load->view('content', $data);
}
}
//view file
<?php $this->load->view('header'); ?>
<p>The data from the controller</p>
<?php $this->load->view('footer'); ?>
I've seen it done both ways, but want to choose now before I go too far down a path.
Actually, after researching this quite a bit myself, I came to the conclusion that the best practice for including headers and footers in MVC is a third option - namely extending a base controller. That will give you a little more flexibility than the text's suggestion, particularly if you're building a very modular layout (not just header and footer, also sidebar panels, non-static menus, etc.).
First, define a Base_controller class, in which you create methods that append your page elements (header, footer, etc.) to an output string:
class Base_controller extends Controller
{
var $_output = '';
function _standard_header($data=null)
{
if (empty($data))
$data = ...; // set default data for standard header here
$this->_output .= $this->load->view('header', $data, true);
}
function _admin_header($data=null)
{
if (empty($data))
$data = ...; // set default data for expanded header here
$this->_output .= $this->load->view('admin_header', $data, true);
}
function _standard_page($data)
{
$this->_standard_header();
$this->_output .=
$this->load->view('standard_content', $data, true);
echo $this->_output; // note: place the echo statement in a
// separate function for added flexibility
}
function _page_with_admin_header($data)
{
$this->_admin_header($data);
$this->_output .=
$this->load->view('standard_content', $data, true);
echo $this->_output;
}
}
Then, in your page controllers, simply extend the base class and call your functions to build the page.
class Page_controller extends Base_controller
{
function index()
{
$data = ...; // Set content data here
$this->_standard_page($data);
}
function admin()
{
$data = ...; // Set content and header data here
$this->_page_with_admin_header($data);
}
}
Using a base controller, you can achieve very clean code in your individual page controllers AND have separate views for elements on the page (allowing code reuse in both views and controllers). All you need to do is define your common page 'sections' (what you might be tempted to call 'fragments') as functions in your base controller.
And if the base controller should start to grow uncontrollably (which can happen on large sites), you can rearrange some of its less-general functions by placing them in subclasses and letting the corresponding page controllers extend those instead of the original base controller.
Enjoy!
You could also try it this way -- define a default view template, which then pulls in the content based on a variable ('content' in my example) passed by the controller.
In your controller:
$data['content'] = 'your_controller/index';
// more code...
$this->load->vars($data);
$this->load->view('layouts/default');
Then define a default layout for all pages e.g. views/layouts/default.php
// doctype, header html etc.
<div id="content">
<?= $this->load->view($content) ?>
</div>
// footer html etc.
Then your views can just contain the pure content e.g. views/your_controller/index.php might contain just the variables passed from the controller/data array
<?= $archives_table ?>
<?= $pagination ?>
// etc.
More details on the CI wiki/FAQ -- (Q. How do I embed views within views? Nested templates?...)
I think the first way you are doing it is cleaner. Simply from a point of view of knowledge that is going to be rendered. Rather than having to enter the view file to find the rest.
It's bad practice to call views inside of other views. This could be a form of controller view mixing. The view function in CI allows you to pass a third parameter that causes it to return that view's output as a string. You can use this to create a compound view.
For example:
class Page extends Controller {
function index() {
$data['page_title'] = 'Your title';
$this->load->view('default_layout', array(
'header' => $this->load->view('header' , array(), true),
'menu' => $this->load->view('menu' , array(), true),
'content' => $this->load->view('content', $data , true),
'footer' => $this->load->view('footer' , array(), true),
));
}
}
default_layout.php
<? echo $header, $menu, $content, $footer; ?>
You may want to combine your header and footer to make a template like this.
class Page extends Controller {
function index() {
$data['page_title'] = 'Your title';
$this->load->view('default_template', array(
'menu' => $this->load->view('menu' , array(), true),
'content' => $this->load->view('content', $data , true),
));
}
}
default_template.php
<html><head></head><body><span>Some Header HTML</span> // this is your header html
<? echo $menu, $content; ?>
<span>some footer HTML</span></body></html> // this is your footer html