I have Theses(datamodel) and Subject(datamodel) and Author(datamodel) i want to display my results grouped by subject
e.g.
Subject1
-Theses1
-Theses2
Subject2
-Theses3
...
what i have so far is the following
<?php
class ThesisDissertations extends Page {
}
class ThesisDissertations_Controller extends Page_Controller {
public function getSubject() {
$subjectgroup = new PaginatedList(Subject::get());
return $subjectgroup;
}
public function ThesesDissertations() {
$pages = new PaginatedList(Theses::get()
->leftJoin("Author", "Theses.AuthorID = Author.ID")
->leftJoin("Subject", "Theses.SubjectID = Subject.ID")
->where("Theses.SubjectID = 'getSubject'")
->sort('SubjectTitle'), $this->getRequest());
$pages->setPageLength(15);
return $pages;
}
}
and for the template
<div class="container"><ul><% loop $getSubject %>
$SubjectTitle
<br>
<% loop $ThesesDissertations %>
<!-- Trigger the modal with a button -->
<li><strong>$Author.AuthorName</strong></li>
<!-- Modal -->
<div id="$ID" class="modal fade" role="dialog">
<div class="modal-dialog modal-lg">
<!-- Modal content-->
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal">×</button>
<h4 class="modal-title"><strong>$TitleTH</strong></h4>
<em>$CallNo, $Author.AuthorName </em>
</div>
<div class="modal-body">
<p class="text-justify">$Summary<br>Subjects : <em>$Subject.SubjectTitle</em>
<hr>
<em><strong>Physical Description :</strong> <% if $PhysicalDesc="" %>No Description Available<% else %>$PhysicalDesc<% end_if %><br>
<strong>Degree Course :</strong> $DegreeCourse<br>
<strong>Year Published :</strong> $Year</em></p>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-danger" data-dismiss="modal">Close</button>
</div>
</div>
</div>
</div><br><% end_loop %><% end_loop %></ul></div>
Subject DataObject
class Subject extends DataObject{
private static $db = array (
'SubjectTitle' => 'Varchar',
);
private static $has_many = array (
'Theses' => 'Theses',
);
public function canView($member = null) {
return Permission::check('CMS_ACCESS_MyAdmin', 'any', $member);
}
public function canEdit($member = null) {
return Permission::check('CMS_ACCESS_MyAdmin', 'any', $member);
}
public function canDelete($member = null) {
return Permission::check('CMS_ACCESS_MyAdmin', 'any', $member);
}
public function canCreate($member = null) {
return Permission::check('CMS_ACCESS_MyAdmin', 'any', $member);
}
private static $summary_fields = array(
'SubjectTitle',
);
}
?>
Theses Dataobject
class Theses extends DataObject{
private static $db = array (
'CallNo' => 'Varchar',
'AuthorID' => 'Int',
'TitleTH' => 'Text',
'Year' => 'Int(4)',
'PhysicalDesc' => 'Text',
'Notes' => 'Text',
'Summary' => 'Text',
'SubjectID' => 'Int',
'DegreeCourse' => 'Varchar',
);
private static $has_one = array (
'Author' => 'Author',
'Subject' => 'Subject',
);
private static $field_labels = array(
'CallNo' => 'Call Number',
'TitleTH' => 'Title Headings',
'Author.AuthorName'=>'Author',
'DegreeCourse'=>'Degree Course',
'Year'=>'Year Published',
'Subject.SubjectTitle'=>'Subject',
);
private static $summary_fields = array (
'CallNo' => 'CallNo',
'TitleTH' => 'TitleTH',
'Author.AuthorName',
'DegreeCourse',
'Year'=>'Year',
'Subject.SubjectTitle',
);
public function getCMSfields() {
$fields = FieldList::create(TabSet::create('Root'));
$fields->addFieldsToTab('Root.Main', array(
TextField::create('CallNo'),
DropdownField::create('AuthorID','AuthorName')->setEmptyString('-Select one-')->setSource(Author::get()->sort('AuthorName')->map('ID','AuthorName')),
TextField::create('TitleTH'),
NumericField::create('Year','Year')->setMaxLength(4),
TextField::create('PhysicalDesc'),
TextField::create('Notes'),
TextAreaField::create('Summary'),
DropdownField::create('DegreeCourse','DegreeCourse',array('BLIS' => 'BLIS','BLS' => 'BLS','MLIS' => 'MLIS','MLS' => 'MLS')),
DropdownField::create('SubjectID','SubjectTitle')->setEmptyString('-Select one-')->setSource(Subject::get()->sort('SubjectTitle')->map('ID','SubjectTitle')),
));
return $fields;
}
}
?>
Author dataobject[if you ever wanted]
class Author extends DataObject{
private static $db = array (
'AuthorName' => 'Varchar',
);
private static $has_many = array (
'Theses' => 'Theses',
);
public function canView($member = null) {
return Permission::check('CMS_ACCESS_MyAdmin', 'any', $member);
}
public function canEdit($member = null) {
return Permission::check('CMS_ACCESS_MyAdmin', 'any', $member);
}
public function canDelete($member = null) {
return Permission::check('CMS_ACCESS_MyAdmin', 'any', $member);
}
public function canCreate($member = null) {
return Permission::check('CMS_ACCESS_MyAdmin', 'any', $member);
}
private static $summary_fields = array(
'AuthorName',
); }?>
I'm not really sure what you've got exactly. In your datamodels, I take it that every thesis has a subject, and every subject can have multiple theses, and that these relations are defined in your models. Then you can supply your template with a list of subjects. You don't have to use a controller function for that. So just add "Subjects" => Subject::get() to the array that you pass to the template, and you can do the following: (shortened and untested, but you'll get the drift):
<% loop $Subjects %>
$SubjectTitle
<% loop $Theses %>
$CallNo, $Author.AuthorName
<% endloop %>
<% endloop %>
When you want to have Subjects available to the template, you can do the following.
In the page controller (in your case ThesisDissertations_Controller), add the following function:
public function index() {
return array("Subjects" => Subject::get());
}
You can pass all kinds of information to the template this way.
Related
I have tried to creating form but data are not save in database table.
I have written the following code.
view/common/home.tpl:
<form action="" method="post" enctype="multipart/form-data" class="form-horizontal form" id="contact">
<legend><?php echo $text_form; ?></legend>
<div class="form-group required">
<label class="col-sm-3 control-label" for="input_first_name"><?php echo $entry_first_name; ?></label>
<div class="col-sm-9">
<input type="text" name="first_name" value="<?php echo $first_name; ?>" id="input_first_name" class="form-control" />
<?php if ($error_first_name) { ?>
<div class="text-danger"><?php echo $error_first_name; ?></div>
<?php } ?>
</div>
</div>
<div class="buttons">
<div class="pull-right">
<input class="btn btn-primary" type="submit" name="submit" value="<?php echo $button_submit; ?>" />
</div>
</div>
</form>
controller/common/home.php
class ControllerCommonHome extends Controller
{
public function index() {
if (isset($this->request->get['route'])) {
$this->document->addLink(HTTP_SERVER, 'canonical');
}
$this->load->language('common/home');
$this->document->setTitle($this->language->get('heading_title'));
$data['breadcrumbs'] = array();
$data['breadcrumbs'][] = array(
'text' => $this->language->get('text_home'),
'href' => $this->url->link('common/home')
);
$data['breadcrumbs'][] = array(
'text' => $this->language->get('text_account'),
'href' => $this->url->link('common/home', '', 'SSL')
);
$url = '';
if (isset($this->request->get['page'])) {
$url .= '&page=' . $this->request->get['page'];
}
$data['breadcrumbs'][] = array(
'text' => $this->language->get('heading_title'),
'href' => $this->url->link('common/home', $url, 'SSL')
);
$data['heading_title'] = $this->language->get('heading_title');
if (isset($this->request->get['page'])) {
$page = $this->request->get['page'];
} else {
$page = 1;
}
$data['returns'] = array();
$data['id'] = $this->language->get('id');
$data['first_name'] = $this->language->get('first_name');
$data['button_continue'] = $this->language->get('button_continue');
$this->load->model('common/home');
$data['column_left'] = $this->load->controller('common/column_left');
$data['column_right'] = $this->load->controller('common/column_right');
$data['content_top'] = $this->load->controller('common/content_top');
$data['content_bottom'] = $this->load->controller('common/content_bottom');
$data['footer'] = $this->load->controller('common/footer');
$data['header'] = $this->load->controller('common/header');
if (file_exists(DIR_TEMPLATE . $this->config->get('config_template') . '/template/common/home.tpl')) {
$this->response->setOutput($this->load->view($this->config->get('config_template') . '/template/common/home.tpl', $data));
} else {
$this->response->setOutput($this->load->view('default/template/common/home.tpl', $data));
}
}
public function add() {
$this->load->language('common/home');
$this->load->model('common/home');
if (($this->request->server['REQUEST_METHOD'] == 'POST') && $this->validate()) {
$return_id = $this->model_common_home->addCustomerbook($this->request->post);
// Add to activity log
$this->load->model('common/home');
$this->response->redirect($this->url->link('common/home/success', '', 'SSL'));
}
$this->document->setTitle($this->language->get('heading_title'));
$this->document->addScript('catalog/view/javascript/jquery/datetimepicker/moment.js');
$this->document->addScript('catalog/view/javascript/jquery/datetimepicker/bootstrap-datetimepicker.min.js');
$this->document->addStyle('catalog/view/javascript/jquery/datetimepicker/bootstrap-datetimepicker.min.css');
$data['breadcrumbs'] = array();
$data['breadcrumbs'][] = array(
'text' => $this->language->get('text_home'),
'href' => $this->url->link('common/home')
);
$data['breadcrumbs'][] = array(
'text' => $this->language->get('text_account'),
'href' => $this->url->link('common/home', '', 'SSL')
);
$data['breadcrumbs'][] = array(
'text' => $this->language->get('heading_title'),
'href' => $this->url->link('common/home/add', '', 'SSL')
);
$data['heading_title'] = $this->language->get('heading_title');
$data['text_first'] = $this->language->get('text_first');
$data['entry_first_name'] = $this->language->get('entry_first_name');
$data['button_submit'] = $this->language->get('button_submit');
$data['button_back'] = $this->language->get('button_back');
if (isset($this->error['warning'])) {
$data['error_warning'] = $this->error['warning'];
} else {
$data['error_warning'] = '';
}
if (isset($this->error['order_id'])) {
$data['error_order_id'] = $this->error['order_id'];
} else {
$data['error_order_id'] = '';
}
if (isset($this->error['first_name'])) {
$data['error_first_name'] = $this->error['first_name'];
} else {
$data['error_first_name'] = '';
}
$data['action'] = $this->url->link('common/home/add', '', 'SSL');
if (isset($this->request->post['firstname'])) {
$data['firstname'] = $this->request->post['firstname'];
} elseif (!empty($order_info)) {
$data['firstname'] = $order_info['firstname'];
} else {
$data['firstname'] = $this->customer->getFirstName();
}
// Captcha
if ($this->config->get($this->config->get('config_captcha') . '_status') && in_array('return', (array)$this->config->get('config_captcha_page'))) {
$data['captcha'] = $this->load->controller('captcha/' . $this->config->get('config_captcha'), $this->error);
} else {
$data['captcha'] = '';
}
$data['back'] = $this->url->link('common/home', '', 'SSL');
$data['column_left'] = $this->load->controller('common/column_left');
$data['column_right'] = $this->load->controller('common/column_right');
$data['content_top'] = $this->load->controller('common/content_top');
$data['content_bottom'] = $this->load->controller('common/content_bottom');
$data['footer'] = $this->load->controller('common/footer');
$data['header'] = $this->load->controller('common/header');
if (file_exists(DIR_TEMPLATE . $this->config->get('config_template') . '/template/account/return_form.tpl')) {
$this->response->setOutput($this->load->view($this->config->get('config_template') . '/template/account/return_form.tpl', $data));
} else {
$this->response->setOutput($this->load->view('default/template/account/return_form.tpl', $data));
}
}
protected function validate() {
.......
}
public function success() {
$this->load->language('common/home');
$this->document->setTitle($this->language->get('heading_title'));
$data['breadcrumbs'] = array();
$data['breadcrumbs'][] = array(
'text' => $this->language->get('text_home'),
'href' => $this->url->link('common/home')
);
$data['breadcrumbs'][] = array(
'text' => $this->language->get('heading_title'),
'href' => $this->url->link('account/return', '', 'SSL')
);
$data['heading_title'] = $this->language->get('heading_title');
$data['text_message'] = $this->language->get('text_message');
$data['button_continue'] = $this->language->get('button_continue');
$data['continue'] = $this->url->link('common/home');
$data['column_left'] = $this->load->controller('common/column_left');
$data['column_right'] = $this->load->controller('common/column_right');
$data['content_top'] = $this->load->controller('common/content_top');
$data['content_bottom'] = $this->load->controller('common/content_bottom');
$data['footer'] = $this->load->controller('common/footer');
$data['header'] = $this->load->controller('common/header');
if (file_exists(DIR_TEMPLATE . $this->config->get('config_template') . '/template/common/success.tpl')) {
$this->response->setOutput($this->load->view($this->config->get('config_template') . '/template/common/success.tpl', $data));
} else {
$this->response->setOutput($this->load->view('default/template/common/success.tpl', $data));
}
}
}
model/common/home.php
class ModelCommonHome extends Model {
public function addCustomerbook($data) {
$this->event->trigger('pre.home.add', $data);
$this->db->query("INSERT INTO `" . DB_PREFIX . "contact_book` SET contact_id = '" . (int)$data['id'] . "', first_name = '" . $this->db->escape($data['first_name']) . "' ");
$id = $this->db->getLastId();
$this->event->trigger('post.home.add', $id);
return $id;
}
I'm not too good at MVC so please help me out to solve this problem.
Sujit, You need to check opencart contact us form functionality for post date to controller. Contact us form does not store data to database but you will make following changes on controller file
$this->load->model('catalog/contact');
$this->model_catalog_contact->addContact($this->request->post;
model/Catalog/contact.php
Create addContact($data) function on it and then make insert query as you know that.
I have TeamsPage class and Team class. I am trying to figure out how to pre-populate the form with the data from the database based on the ID that was passed in the URL. Below is the code of my attempt, I tried to pass in the ID via template but that did not work. How else can I accomplish this? I would prefer if there was a way to pass the team as an object that I already have in the edit function so that I don't have to hit the database twice. Is there a way to do this?
TeamsPage:
<?php
class TeamsPage extends Page {
private static $has_many = array (
'Teams' => 'Team',
);
public function getCMSFields() {
$fields = parent::getCMSFields();
$fields->addFieldToTab('Root.Teams', GridField::create(
'Teams',
'Teams on this page',
$this->Teams(),
GridFieldConfig_RecordEditor::create()
));
return $fields;
}
}
class TeamsPage_Controller extends Page_Controller {
private static $allowed_actions = array (
'show', 'edit', 'EditTeamForm'
);
public function EditTeamForm($teamId){
$fields = new FieldList(
new TextField('TeamName'),
new TextareaField('TeamDescription')
);
$actions = new FieldList(
new FormAction('EditTeam', 'Save Changes')
);
$requiredFields = new RequiredFields(array('TeamName','TeamDescription'));
$form = new Form($this, 'EditTeamForm', $fields, $actions, $requiredFields);
$form->setFormMethod('POST', true);
$data = Session::get("FormData.{$form->getName()}.data");
$team = Team::get()->byID($teamId);
return $data ? $form->loadDataFrom($data) : $form->loadDataFrom($team);
}
public function show(SS_HTTPRequest $request) {
$team = Team::get()->byID($request->param('ID'));
if(!$team) {
return $this->httpError(404,'That team could not be found');
}
return array (
'Team' => $team
);
}
public function edit(SS_HTTPRequest $request){
$team = Team::get()->byID($request->param('ID'));
if(!$team) {
return $this->httpError(404,'That team could not be found');
}
return array (
'Team' => $team
);
}
}
Team:
<?php
class Team extends DataObject {
private static $db = array(
'TeamCaptain' => 'Int',
'TeamName' => 'Varchar',
'TeamDescription' => 'Text'
);
private static $has_one = array (
'Photo' => 'Image',
'TeamsPage' => 'TeamsPage'
);
private static $summary_fields = array (
'GridThumbnail' => '',
'TeamCaptain' => 'Team Captain',
'TeamName' => 'TeamName',
'TeamDescription' => 'Team Description',
);
public function getGridThumbnail() {
if($this->Photo()->exists()) {
return $this->Photo()->SetWidth(100);
}
return '(no image)';
}
public function getCMSFields() {
$fields = FieldList::create(
TextField::create('TeamCaptain'),
TextField::create('TeamName'),
TextareaField::create('TeamDescription'),
$uploader = UploadField::create('Photo')
);
$uploader->setFolderName('teams-photos');
$uploader->getValidator()->setAllowedExtensions(array(
'png','gif','jpeg','jpg'
));
return $fields;
}
public function Link() {
return $this->TeamsPage()->Link('show/'.$this->ID);
}
}
TeamsPage_edit.ss
<% if GetMember() %>
Welcome $getMember.FirstName<br />
$EditTeamForm($ID)
Back to Home
<% else %>
$GoToLogin()
<% end_if %>
It looks to me like you're passing the wrong ID to EditTeamForm from the template. Unless there is a <% with %> statement that I'm not seeing I think you want to call:
$EditTeamForm($Team.ID)
Everything else looks fine to me.
I have two password fields. That extra is for confirmation.
And there is no error message when both are empty or when passwords don't match.
How to enable or debug this validation which I presume should be working out of the box (http://symfony.com/doc/current/reference/forms/types/repeated.html#validation)?
class MyType extends AbstractType
{
public function setDefaultOptions(OptionsResolverInterface $resolver)
{
$resolver->setDefaults(array(
'data_class' => 'My\\Bundle\\Entity\\User',
));
}
public function buildForm(FormBuilderInterface $builder, array $options)
{
...
$builder->add('password', 'repeated', array(
'invalid_message' => 'Passwords must match.',
'type' => 'password',
'required' => true,
'first_options' => array('label' => 'Password'),
'second_options' => array('label' => 'Repeat Password')
));
form.html.twig
...
<form action="" method="post" novalidate>
...
<tr>
<td>{{ form_label(regForm.password.first) }}</td>
<td>{{ form_widget(regForm.password.first, { 'attr': {'pattern': '.{6,}','title': 'Minimum 6 characters long'} } ) }}</td>
</tr>
<tr>
<td>{{ form_label(regForm.password.second) }}</td>
<td>{{ form_widget(regForm.password.second, { 'attr': {'pattern': '.{6,}', 'title': 'Minimum 6 characters long', 'data-equals': '#register_password_first'} } ) }}</td>
</tr>
Validators declared in validation.yml seem to have no effect on the issue.
My\Bundle\Entity\User:
properties:
...
password:
# this one does not work because of "repeated" type in buildForm()???
- NotBlank:
message: "Password is required."
- MinLength:
limit: 6
message: "Password must have at least {{ limit }} characters."
Controller.php (original version)
...
if (!$form->isValid()) {
$formFields = $form->all();
foreach ($formFields as $key => $field) {
if ($field->getErrorsAsString()) {
$errors = $field->getErrors();
foreach ($errors as $error) {
$messages[$key][] = $error->getMessage();
}
}
}
var_dump($messages);
EDIT: Now errors retrieval looks like this (thanks to alex.dominte):
public static function getFormErrorMessages(\Symfony\Component\Form\Form $form)
{
$messages = array();
foreach ($form->getErrors() as $i => $error) {
$messages[$i] = $error->getMessage();
}
foreach ($form->all() as $child) {
if (!$child->isValid()) {
$messages[$child->getName()] = self::getFormErrorMessages($child);
}
}
return $messages;
}
Modifications suggested by Pedro Cordeiro make it possible to drop recursion but also make field names unavailable.
Two things missing from your definitions:
1) error_bubbling must be manually set to TRUE on your fields, so they can throw errors in the ->getErrors() function.
2) cascade_validation is FALSE by default, you must add it too to your parent forms ($builder->add('propertyName', new YourFormNameType(), array('cascade_validation ' => true));) - See this
Not enough recursion
foreach ($formFields as $key => $field) {
if ($field->getErrorsAsString()) {
$errors = $field->getErrors();
foreach ($errors as $error) {
$messages[$key][] = $error->getMessage();
}
}
}
Try this - should work for all nested errors:
class FormHelper
{
public static function getErrorMessages($form)
{
$errors = array();
if (!$form->isBound()) return $errors;
foreach ($form->getErrors() as $key => $error) {
$template = $error->getMessageTemplate();
$parameters = $error->getMessageParameters();
foreach ($parameters as $var => $value) {
$template = str_replace($var, $value, $template);
}
$errors[$key] = $template;
}
if ($form->hasChildren()) {
foreach ($form->getChildren() as $child) {
if (!$child->isValid()) {
$name = $child->getConfig()->getOption('title', $child->getName());
$errors[$name] = self::getErrorMessages($child);
}
}
}
return $errors;
}
}
you do not show error message
{{ form_errors(regForm.password.first) }}
{{ form_errors(regForm.password.second) }}
I just started at Zend Framework and i have some issues,
When i use the URL function, which is inside a placeholder called "menu-gerenciador" that is in the "painel" layout, thats the default layout i use in the "painel" controller(/gerenciador/painel) it renders the right url:
this:
<a href="<?php echo $this->url(array("module" => "gerenciador", "controller" => "usuarios", "action" => "listar")); ?>">
Becomes this:
<a href="/gerenciador/usuarios/listar">
But when i click this link, i got redirected back to /gerenciador/painel
The directory of my application:
-application
--configs
--forms
--layouts
--modules
---default
----controllers
-----IndexController
-----LoginController
----models
----views
---gerenciador
----controllers
-----PainelController
-----UsuariosController
----models
----views
-data
-public
-library
-tests
Painel Controller:
class Gerenciador_PainelController extends Zend_Controller_Action
{
public function init()
{
$this->_helper->layout->setLayout('painel');
$auth = Zend_Auth::getInstance();
if(!$auth->hasIdentity()) {
$this->_redirect($this->view->url(array('module' => 'default', 'controller' => 'login')));
}
$this->view->usuario = $auth->getIdentity();
}
public function preDispatch()
{
$this->view->render('painel/menu.phtml');
}
public function indexAction()
{
}
public function logoutAction()
{
$auth = Zend_Auth::getInstance();
$auth->clearIdentity();
$this->_redirect($this->view->url(array('module' => 'default', 'controller' => 'index', 'action' => 'index')));
}
}
Painel Menu(witch is in a placeholder inside the painel layout(has the link)):
<?php $this->placeholder('menu-gerenciador')->captureStart() ?>
<div id="menu-painel">
<h3>Gerenciador</h3>
<div>
<ul class="menulista">
<a href="<?php echo $this->url(array("module" => "gerenciador", "controller" => "painel")); ?>">
<li>Inicial</li>
</a>
<a href="<?php echo $this->url(array("module" => "gerenciador", "controller" => "usuarios", "action" => "listar")); ?>">
<li>Usuarios</li>
</a>
<li>Banner</li>
<li>Pagina Empresa</li>
<li>Configuracoes</li>
</ul>
</div>
</div>
<?php $this->placeholder('menu-gerenciador')->captureEnd() ?>
And Finally the Usuarios Controller where it should be redirected by the link:
<?php
class Gerenciador_UsuariosController extends Zend_Controller_Action
{
public function init()
{
$this->_helper->layout->setLayout('painel');
$this->view->headLink()->appendStylesheet($this->view->baseUrl('css/bootstrap/bootstrap.css'));
$auth = Zend_Auth::getInstance();
if($auth->hasIdentity()) {
$this->_redirect($this->view->url(array('module' => 'default', 'controller' => 'login'), null, TRUE));
}
}
public function indexAction()
{
$this->_redirect($this->view->url(array(
"module" => "gerenciador",
"controller" => "usuarios",
"action" => "listar"
)));
}
public function listarAction()
{
$model = new Gerenciador_Model_Usuario();
$this->view->listaUsu = $model->listar();
}
}
I already tried to put the reset param TRUE inside my URL function, but this dont work as well.
I dont know why it keeps redirecting to the same page
In Usuarios Controller in the init method you have the line:
if($auth->hasIdentity()) {
Shouldnt that be:
if(!$auth->hasIdentity()) {
Otherwise logged in users are always redirected away from that controller
I use Zend Framework and in my application admin is mostly used for CRUD operations.
I don't use zend form, and I want to keep it that way if possible, but I think that my code is not good at all, and that it can be improved allot so I am asking nicely you how to organize better this class (since all my classes look prety much the same)...
Here is the code:
http://pastie.org/2422147
honestly the improvement would be to use Zend_Form. What is you reasoning for not using Zend_Form? If it is that you cannot get the custom look and feel you require using decorators, there are ways to leverage zend_Form without mucking with that stuff.
Sample Admin CRUD Controller (for hierarchical categories)
class StoreAdmin_CategoryController extends Zend_Controller_Action
{
protected $_flashMessenger = null;
public function init()
{
$this->_flashMessenger = $this->_helper->getHelper('FlashMessenger');
$this->initView();
}
public function indexAction()
{
$this->_forward('list');
}
public function listAction()
{
$table_category = new Store_Model_DbTable_Category();
$obj_select = $table_category->build_select(array(), array('order_by' => 'ASC'));
$arr_categories = $table_category->fetch_all_objects($obj_select);
$table_category = new Store_Model_DbTable_Category();
$hierarchy = $table_category->get_hierarchy(NULL);
$this->view->assign('arr_categories', $arr_categories);
$this->view->assign('hierarchy', $hierarchy);
}
public function createAction()
{
$form = new StoreAdmin_Form_Category();
if($this->getRequest()->isPost())
{
if($form->isValid($this->getRequest()->getPost()))
{
$table_category = new Store_Model_DbTable_Category();
$category = $table_category->get();
$category->set_name($form->getValue('name'));
$category->set_slug($form->getValue('slug'));
$category->set_description($form->getValue('description'));
$category->set_order_by($form->getValue('order_by'));
$category->set_id_parent($form->getValue('id_parent'));
$category->set_date_created(time());
$category->set_date_modified(time());
$table_category->save($category);
$this->_helper->FlashMessenger(array('success' => sprintf("Category: %s was successfully created!", $category->get_name())));
$this->_redirect('/store-admin/category/list');
}
else
{
$this->_helper->FlashMessenger(array('error' => "Errors! Correct the errors in the form below"));
}
}
$this->view->assign('form_category', $form);
}
public function updateAction()
{
$id_category = $this->getRequest()->getParam('id_category');
if(empty($id_category))
{
throw new Zend_Exception('Error: Category ID Missing from request');
}
$form = new StoreAdmin_Form_Category();
$form->removeOption($id_category);
$table_category = new Store_Model_DbTable_Category();
$category = $table_category->get($id_category);
if($this->getRequest()->isPost())
{
if($form->isValid($this->getRequest()->getPost()))
{
$category->set_name($form->getValue('name'));
$category->set_slug($form->getValue('slug'));
$category->set_description($form->getValue('description'));
$category->set_order_by($form->getValue('order_by'));
$category->set_id_parent($form->getValue('id_parent') ? $form->getValue('id_parent') : NULL);
$category->set_date_modified(time());
$table_category->save($category);
$this->_helper->FlashMessenger(array('success' => sprintf("Category: %s was successfully updated!", $category->get_name())));
$this->_redirect('/store-admin/category/list');
}
else
{
$this->_helper->FlashMessenger(array('error' => "Errors! Correct the errors in the form below"));
}
}
else
{
$form->populate($category->to_array());
}
$this->view->assign('form_category', $form);
$this->view->assign('category', $category);
}
public function deleteAction()
{
$id_category = $this->getRequest()->getParam('id_category');
if(empty($id_category))
{
throw new Zend_Exception('Error: Category ID Missing from request');
}
$table_category = new Store_Model_DbTable_Category();
$category = $table_category->get($id_category);
$table_category->destroy($category);
$this->_helper->FlashMessenger(array('success' => "Category was successfully deleted!"));
$this->_redirect('/store-admin/category/list');
}
}
Sample create view
<div class="span-24">
List
<form action="<?php echo $this->form_category->getAction(); ?>" method="<?php echo $this->form_category->getMethod(); ?>">
<h2>Create a Category</h2>
<p>
<?php echo $this->form_category->getElement('name')->renderLabel(); ?>
<br>
<?php echo $this->form_category->getElement('name')->renderViewHelper(); ?>
<?php echo (NULL != ($errors = $this->form_category->getElement('name')->getMessages()) ? $this->formErrors($errors) : ''); ?>
</p>
<p>
<?php echo $this->form_category->getElement('slug')->renderLabel(); ?>
<br>
<?php echo $this->form_category->getElement('slug')->renderViewHelper(); ?>
<?php echo (NULL != ($errors = $this->form_category->getElement('slug')->getMessages()) ? $this->formErrors($errors) : ''); ?>
</p>
<p>
<?php echo $this->form_category->getElement('id_parent')->renderLabel(); ?>
<br>
<?php echo $this->form_category->getElement('id_parent')->renderViewHelper(); ?>
<?php echo (NULL != ($errors = $this->form_category->getElement('id_parent')->getMessages()) ? $this->formErrors($errors) : ''); ?>
</p>
<p>
<?php echo $this->form_category->getElement('description')->renderLabel(); ?>
<br>
<?php echo $this->form_category->getElement('description')->renderViewHelper(); ?>
<?php echo (NULL != ($errors = $this->form_category->getElement('description')->getMessages()) ? $this->formErrors($errors) : ''); ?>
</p>
<p>
<?php echo $this->form_category->getElement('order_by')->renderLabel(); ?>
<br>
<?php echo $this->form_category->getElement('order_by')->renderViewHelper(); ?>
<?php echo (NULL != ($errors = $this->form_category->getElement('order_by')->getMessages()) ? $this->formErrors($errors) : ''); ?>
</p>
<p>
<?php echo $this->form_category->getElement('submit_category')->renderViewHelper(); ?>
</p>
</form>
</div>
<script type="text/javascript">
$(document).ready(
function()
{
$('#name').change( slugify ).keyup( slugify );
}
);
function slugify()
{
text = $(this).val().toLowerCase();
text = text.replace(/[^-a-zA-Z0-9,&\s]+/ig, '');
text = text.replace(/-/gi, "_");
text = text.replace(/\s/gi, "-");
$('#slug').val(text);
}
</script>
Sample Category Form
<?php
class StoreAdmin_Form_Category extends Zend_Form
{
public function init()
{
$this->setMethod(self::METHOD_POST);
$element = $this->createElement('hidden', 'id_category');
$element->removeDecorator('DtDdWrapper');
$element->removeDecorator('label');
$this->addElement($element);
$element = $this->createElement('text', 'name');
$element->setLabel('Name');
$element->setRequired(TRUE);
$element->removeDecorator('DtDdWrapper');
$element->setAttrib('class', 'text');
$this->addElement($element);
$element = $this->createElement('text', 'slug');
$element->setLabel('Slug');
$element->setRequired(TRUE);
$element->removeDecorator('DtDdWrapper');
$element->setAttrib('class', 'text');
$this->addElement($element);
$element = $this->createElement('textarea', 'description');
$element->setLabel('Description');
$element->removeDecorator('DtDdWrapper');
$element->setAttrib('class', '');
$this->addElement($element);
$table_category = new Store_Model_DbTable_Category();
$options = $table_category->get_tree_options(NULL, '', array(NULL => ''));
$element = $this->createElement('select', 'id_parent');
$element->setLabel('Parent Category');
$element->setRequired(FALSE);
$element->removeDecorator('DtDdWrapper');
$element->addMultiOptions($options);
$this->addElement($element);
$element = $this->createElement('text', 'order_by');
$element->setLabel('Display Order');
$element->setRequired(TRUE);
$element->removeDecorator('DtDdWrapper');
$element->setAttrib('class', 'text');
$this->addElement($element);
$element = $this->createElement('submit', 'submit_category');
$element->setLabel('Submit');
$element->setRequired(TRUE);
$element->removeDecorator('DtDdWrapper');
$element->removeDecorator('label');
$this->addElement($element);
}
/**
* Makes sure that a Category cannot become its own parent (causing a rescursion error)
*/
public function removeOption($id_category)
{
$this->removeElement('id_parent');
$table_category = new Store_Model_DbTable_Category();
$options = $table_category->get_tree_options(NULL, '', array(NULL => ''));
if(array_key_exists($id_category, $options))
{
unset($options[$id_category]);
}
$element = $this->createElement('select', 'id_parent');
$element->setLabel('Parent Category');
$element->setRequired(FALSE);
$element->removeDecorator('DtDdWrapper');
$element->addMultiOptions($options);
$this->addElement($element);
}
}
Zend_Form greatly simplifies crud controllers. More importantly, it is the accepted practice to use them if you are going to be building apps on ZF.