Never been to DZone Snippets before?

Snippets is a public source code repository. Easily build up your personal collection of code snippets, categorize them with tags / keywords, and share them with the world

« Newer Snippets
Older Snippets »
Showing 1-4 of 4 total  RSS 

Zend Framework view helper for generating menus

<?php
/**
 * ----------------------------------------------------------------
 * Copyright (C) 2008 Agencja Interaktywna Blue Paprica
 *                    Maciej Pałubicki. All rights reserved.
 * ----------------------------------------------------------------
 *
 * /framework/application/Modules/Admin/views/helpers/Menu.php
 *
 * @author      Łukasz Kazimierz Bandzarewicz <lukasz.bandzarewicz@bluepaprica.com>
 * @copyright   Copyright (C) 2008 Agencja Interaktywna Blue Paprica
 *                                 Maciej Pałubicki. All rights reserved.
 */

class Zend_View_Helper_Menu
{

    protected function _prepareMenu()
    {
        return array(
                array(
                'title' => 'Strona główna',
                'controller' => 'index'
            )

            , array(
                'title' => 'Użytkownicy systemu',
                'controller' => 'users',
            )

            , array(
                'title' => 'System Punktów',
                'controller' => 'point_categories',
            )

            , array(
                'title' => 'Produkty',
                'controller' => 'store_products',

                'submenu' => array(
                    array(
                        'title' => 'Lista produktów',
                        'action' => 'list'
                    ),
                    array(
                        'title' => 'Dodaj produkt',
                        'action' => 'create'
                    )
                )
            )

            , array(
                'title' => 'Kupony',
                'controller' => 'store_coupons',

                'submenu' => array(
                    array(
                        'title' => 'Lista kuponów',
                        'action' => 'list'
                    ),
                    array(
                        'title' => 'Dodaj kupon',
                        'action' => 'create'
                    )
                )
            )

            , array(
                'title' => 'Kategorie produktów',
                'controller' => 'store_categories',

                'submenu' => array(
                    array(
                        'title' => 'Lista kategorii',
                        'action' => 'list'
                    ),
                    array(
                        'title' => 'Dodaj kategorię',
                        'action' => 'create'
                    )
                )
            )

            , array(
                'title' => 'Dostawcy',
                'controller' => 'store_suppliers',

                'submenu' => array(
                    array(
                        'title' => 'Lista producentów',
                        'action' => 'list'
                    ),
                    array(
                        'title' => 'Dodaj producenta',
                        'action' => 'create'
                    )
                )
            )

            , array(
                'title' => 'Producenci',
                'controller' => 'store_manufacturers',

                'submenu' => array(
                    array(
                        'title' => 'Lista producentów',
                        'action' => 'list'
                    ),
                    array(
                        'title' => 'Dodaj producenta',
                        'action' => 'create',
                        'params' => '/type/'
                    )
                )
            )

            , array(
                'title' => 'Aktualności',
                'controller' => 'static_news',
                'action' => 'list',

                'submenu' => array(
                    array(
                        'title' => 'Lista aktualności',
                        'action' => 'list'
                    ),
                    array(
                        'title' => 'Dodaj aktualność',
                        'action' => 'create'
                    )
                )
            )

            , array(
                'title' => 'Strony statyczne',
                'controller' => 'static_pages',
                'action' => 'list'
            )

            , array(
                'title' => 'Logi',
                'controller' => 'maintenance_logs',
            )
        );
    }

    /**
     * @var Zend_View_Interface
     */
    public $view;

    public function setView(Zend_View_Interface $view)
    {
        $this->view = $view;
    }

    public function menu()
    {
        $menu = $this->_prepareMenu();

        $ctrl = Zend_Controller_Front::getInstance();
        $controller = $ctrl->getRequest()->getControllerName();
        $action = $ctrl->getRequest()->getActionName();
?>

<script type="text/javascript">
<!--
var timeoutID;

function displaySubmenu(submenu_id) {
    // hide all elements
    $('ul[id*=bp_submenu_]').each(function(e) {
        $(this).hide();
    });

    // show the chosen one
    $(submenu_id).show();
}

$(document).ready(function () {

    // for each main menu elements
    $('a[@id*=bp_menu_]').each(function(e) {

        var controller = this.id.substring('bp_menu_'.length);
        var submenu_id = '#bp_submenu_' + controller;
        var menu_id = '#bp_menu_' + controller;

        $(menu_id).mouseover(function() {

            timeoutID = setTimeout(function() {
                displaySubmenu(submenu_id);
            }, 1000);

        });

        $(menu_id).mouseout(function() {
            if (timeoutID) {
                clearTimeout(timeoutID);
            }
        });

        $(menu_id).click(function() {
            if ($(submenu_id).is(':hidden')) {
                displaySubmenu(submenu_id);
                return false;
            }
        });

    });

});
//-->
</script>

<div id="bp_menu_1">
    <ul id="bp_menu">
    <? foreach ($menu as $main_menu_item) : ?>
        <li>
           <a
               id="bp_menu_<?= $main_menu_item['controller'] ?>"
               href="<?= $ctrl->getBaseUrl() ?>/admin/<?= $main_menu_item['controller'] ?><? if (isset($main_menu_item['action'])) : ?>/<?= $main_menu_item['action'] ?><? endif; ?>"
               <?php if ($controller == $main_menu_item['controller']) : ?>class="active"<? endif; ?>>
               <?= $this->view->escape($main_menu_item['title']) ?>
               <? if (isset($main_menu_item['submenu'])) : ?>&raquo;<? endif; ?>
           </a>
        </li>
    <? endforeach; ?>
    </ul>
</div>

<div id="bp_menu_2">
<? foreach ($menu as $main_menu_item) : ?>
    <? if (isset($main_menu_item['submenu']) && is_array($main_menu_item['submenu'])) : ?>
    <ul id="bp_submenu_<?= $main_menu_item['controller'] ?>" <? if ($controller != $main_menu_item['controller']) :?>style="display: none;"<? endif; ?>>
        <? foreach ($main_menu_item['submenu'] as $sub_main_menu_item) : ?>
        <li>
            <a
              href="<?= $ctrl->getBaseUrl() ?>/admin/<?= $main_menu_item['controller'] ?>/<?= $sub_main_menu_item['action'] ?>"
              <? if ($controller == $main_menu_item['controller'] && $action == $sub_main_menu_item['action']) :?>class="active"<? endif; ?>>
              <?= $this->view->escape($sub_main_menu_item['title']) ?>
            </a>
            <span></span>
        </li>
        <? endforeach; ?>
    </ul>
    <? endif; ?>
<? endforeach; ?>
</div>

<?php
    }

}

Using a mutiple collection select form helper with habtm or has many associations in Rails

// where user has and belongs to many roles

# in your view
<%= collection_select :user, :role_ids, Role.find(:all, :order => 'name ASC'), :id, :name, { :selected => @user.role_ids }, { :multiple => true, :name => 'user[role_ids][]' } -%>

Helper for quicly creating standard tables

I often want to display an array of objects as a table on a page, and I end up doing the the same things over and over again. I wrote this helper method to speed things up:

def table(collection, headers, options = {}, &proc)
  options.reverse_merge!({
    :placeholder  => 'Nothing to display',
    :caption      => nil,
    :summary      => nil,
    :footer       => ''
  })
  placeholder_unless collection.any?, options[:placeholder] do
    summary = options[:summary] || "A list of #{collection.first.class.to_s.pluralize}"
    output = "<table summary=\"#{summary}\">\n"
    output << content_tag('caption', options[:caption]) if options[:caption]
    output << "\t<caption>#{options[:caption]}</caption>\n" if options[:caption]
    output << content_tag('thead', content_tag('tr', headers.collect { |h| "\n\t" + content_tag('th', h) }))
    output << "<tfoot><tr>" + content_tag('th', options[:footer], :colspan => headers.size) + "</tr></tfoot>\n" if options[:footer]
    output << "<tbody>\n"
    concat(output, proc.binding)
    collection.each do |row|
      proc.call(row, cycle('odd', 'even'))
    end
    concat("</tbody>\n</table>\n", proc.binding)
  end
end


Writing...

<% table(@posts, %w{ID title}) do |post, klass| -%>
    <tr class="<%= klass %>">
      <td><%= post.id</td>
      <td><%= post.title </td>
    </tr>
<% end -%>


results in...

<table summary="A list of posts">
  <thead>
    <tr>
      <th>ID</th>
      <th>Title</th>
    </tr>
  </thead>
  <tfoot><tr><td colspan="2"></td></tr></tfoot>
  <tbody>
    <tr>
      <td>1</td>
      <td>My first post</td>
    </tr>
  </tbody>
</table>


Or, when the collection is an empty array (collection.any? returns false), a placeholder message is displayed:

<p class="placeholder">Nothing to display</p>


So you pass in your collection and an array of strings as your table headers as the first two arguments, and the third is a hash of options you can use to set the contents of the table's summary-attribute, the caption and footer-elements and the placeholder.

The summary attribute defaults to "A list of [objects]", where 'objects' is derived from the class name of the collection.

The function finally takes a block for every element in the collection, yeilding it the element and either 'odd' or 'even' so you can use CSS-classes to apply a zebra stripes effect.

Python - Example Simple ImageView

import pygtk; pygtk.require('2.0')
import gtk

class Image_Example(object):

	def pressButton(self, widget, data=None):
		print "Pressed"

	def delete_event(self, widget, event, data=None):
		print "delete event occured"

		return False

	def destroy(self, widget, data=None):
		gtk.main_quit()

	def __init__(self):
		self.window = gtk.Window(gtk.WINDOW_TOPLEVEL)
		self.window.connect("delete_event", self.delete_event)
		self.window.connect("destroy", self.destroy)
		self.window.set_border_width(10)

		self.button = gtk.Button()
		self.button.connect("clicked", self.pressButton, None)
		self.button.connect_object("clicked", gtk.Widget.destroy, self.window)

		self.image = gtk.Image()
		self.image.set_from_file("/tmp/f27.jpg")
		self.image.show()

		self.button.add(self.image)
		self.window.add(self.button)
		self.button.show()
		self.window.show()

	def main(self):
		gtk.main()


if __name__ == '__main__':

	Image_Example().main()
« Newer Snippets
Older Snippets »
Showing 1-4 of 4 total  RSS