How to improve admin controllers used for crud - zend-framework

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.

Related

CodeIgniter 4: Call to member function on null where post request is valid in var_dump()

** Very new to CodeIgniter so please be kind! **
I have an issue with my two user authentication forms: users/register.php and users/login.php where I cannot pass the post input to functions in my model.
As of now, I'm getting the error Call to member function addUser() on null on the registration form and a validation error on the login form that states the username/password don't match any credentials in the database. Both seem to stem from post being null although it is not.
I have done a var_dump on $login which is defined as $login = $this->request->getPost() as well as inspected the request in Firefox Developers Browser to find all the post data correctly displayed. I am stumped. Why can't I pass this array to my model?
Here is a screenshot of the post request for login.php (the same can be said for registration.php and is not included).
These are my routes:
// Login and Registration
$routes->match(['get', 'post'], 'users/register', 'Users::register');
$routes->match(['get', 'post'], 'users/login', 'Users::login', ["filter" => "noauth"]);
Here is my model UserModel.php in its entirety:
class UserModel extends Model
{
protected $DBGroup = 'default';
protected $table = 'users';
protected $primaryKey = 'username';
protected $useAutoIncrement = false;
protected $insertID = 0;
protected $returnType = 'object';
protected $useSoftDelete = false;
protected $allowedFields = [
'username',
'password',
'id',
'role',
'profile_image',
'profile_views',
'last_login',
'about_me',
'age',
'gender',
'occupation',
'hometown',
'country',
'fav_shape',
'fav_color',
'created',
'modified',
];
// Dates
protected $useTimestamps = true;
protected $dateFormat = 'datetime';
protected $createdField = 'created';
protected $modifiedField = 'modified';
// Callbacks
protected $allowCallbacks = true;
protected $beforeInsert = ['beforeInsert'];
public function __construct()
{
parent::__construct();
}
protected function beforeInsert(array $data)
{
$data = $this->passwordHash($data);
return $data;
}
protected function passwordHash(array $data)
{
if (isset($data['password'])) {
$data['password'] = password_hash($data['password'], PASSWORD_DEFAULT);
}
return $data;
}
public function lastLogin($username)
{
$this->builder()
->where('username', $username)
->update('last_login', date('Y-m-d H:i:s'));
}
public function addUser($newUser)
{
$builder = $this->builder()
->set($newUser)
->insert();
if ($builder->affected_rows() == 1) {
return TRUE;
} else {
return FALSE;
}
}
public function getUser($username)
{
$builder = $this->builder()
->where(['username' => $username])
->limit(1);
if ($builder->countAllResults() === 1) {
return $builder->get()->getRow();
} else {
return FALSE;
}
}
}
Here are excerpts from my controller Users.php:
class Users extends BaseController
{
protected $userModel;
public function __construct()
{
$userModel = new UserModel();
}
public function login()
{
$validation = \Config\Services::validation();
// Set session variable
$session = session();
if ($this->request->getMethod() === 'post' && ! empty($_POST)) {
$validation->getRuleGroup('login');
$validation->setRuleGroup('login');
$validation->withRequest($this->request)->run();
$recaptchaResponse = trim($this->request->getVar('g-recaptcha-response'));
$userIp = $this->request->getIPAddress();
$secret = env('recaptcha2_secretkey');
$credential = [
'secret' => $secret,
'response' => $recaptchaResponse,
'remoteip' => $userIp,
];
$verify = curl_init();
curl_setopt($verify, CURLOPT_URL, 'https://www.google.com/recaptcha/api/siteverify');
curl_setopt($verify, CURLOPT_POST, TRUE);
curl_setopt($verify, CURLOPT_POSTFIELDS, http_build_query($credential));
curl_setopt($verify, CURLOPT_SSL_VERIFYPEER, FALSE);
curl_setopt($verify, CURLOPT_RETURNTRANSFER, TRUE);
$response = curl_exec($verify);
$status = json_decode($response, TRUE);
curl_close($verify);
if (empty($validation->getErrors()) && $status['success']) {
$login = $this->request->getPost();
$user = $this->userModel->getUser($login['username']);
// Storing session values
$this->setUserSession($user);
// Storing success message
$session->setFlashdata('success', 'You have successfully logged in!');
// Update last login datetime
$this->userModel->lastLogin($login['username']);
// Redirecting to dashboard after login
if ($user['role'] == 1) {
return redirect()->to('admin/dashboard');
} elseif ($user['role'] == 0) {
return redirect()->to('members/dashboard');
}
} else {
$data = [
'title' => 'Login',
'errors' => $validation->getErrors(),
];
echo view('templates/index_header', $data);
echo view('users/login');
echo view('templates/footer', $data);
}
} else {
$data = [
'title' => 'Login',
];
echo view('templates/index_header', $data);
echo view('users/login');
echo view('templates/footer', $data);
}
}
/**
* Sets session with user id, username, isLoggedIn, and role for use in member/admin site
* #param model user data
* #return boole if session was set successfully
*/
private function setUserSession($user)
{
$data = [
'id' => $user->id,
'username' => $user->username,
'profile_image' => $user->profile_image,
'isLoggedIn' => true,
'role' => $user->role,
];
if (session()->set($data)) {
return true;
} else {
return false;
}
}
public function register()
{
$validation = \Config\Services::validation();
if ($this->request->getMethod() == 'post' && ! empty($_POST)) {
$validation->getRuleGroup('registration');
$validation->setRuleGroup('registration');
$validation->withRequest($this->request)->run();
if (empty($validation->getErrors())) {
$newUser = $this->request->getPost();
if ($this->userModel->addUser($newUser)) {
$this->session->setFlashdata('success', 'Successful Registration');
$data['title'] = 'Login';
echo view('templates/index_header', $data);
echo view('users/login');
echo view('templates/footer', $data);
} else {
$this->session->setFlashdata('error', 'Something went wrong with your registration! Please try again.');
}
} else {
$data = [];
$data = [
'title' => 'Register',
'script' => 'js/click_link',
'errors' => $validation->getErrors(),
];
echo view('templates/index_header', $data);
echo view('users/register', $data);
echo view('templates/footer', $data);
}
} else {
$data = [
'title' => 'Register',
'script' => 'js/click_link',
];
echo view('templates/index_header', $data);
echo view('users/register', $data);
echo view('templates/footer', $data);
}
}
}
These are my validation rules in Config\Validation:
/**
* Registration
*/
public $registration = [
'username' => 'required|is_unique[users.username,username]|min_length[5]|max_length[25]|alpha_dash|badWordsFilter[username]',
'password' => 'required|min_length[8]|max_length[255]|regex_match[/^(?=.*[!##$%^&*-])(?=.*[0-9])(?=.*[A-Z]).{8,255}$/]',
'pass_confirm' => 'required|matches[password]',
'about_me' => 'permit_empty|max_length[250]|alpha_numeric_punct|badWordsFilter[about_me]',
'occupation' => 'permit_empty|max_length[50]|alpha_space|badWordsFilter[occupation]',
'hometown' => 'permit_empty|max_length[50]|alpha_space|badWordsFilter[hometown]',
'age' => 'permit_empty|less_than[100]|greater_than[0]|numeric',
'country' => 'permit_empty',
];
/**
* Password Verification
*/
public $login = [
'password' => 'required|validateUser[username,password]',
];
This is my custom rule to authenticate username and password credentials User_rules:
class User_rules
{
/**
* Checks if input username exists in database and then checks whether the input password matches the hash for that username
* #param string $str is the input password
* #param string $fields are the associated form fields that are being used
* #param array $data is an array containing the values for the fields indexed by field names
* #return boolean true or false depending on if the user exists and the password matches the hashed password stored in the database
*/
public function validateUser(string $str, string $fields, array $data)
{
$userModel = new UserModel();
$user = $userModel->getUser($data['username']);
if(!$user) {
return FALSE;
}
return password_verify($data['password'], $user->password);
}
Lastly, my view for login.php:
<div class='form-container'>
<?= form_open('users/login',['autocomplete' => FALSE]); ?>
<div class='form-header'>
<h2>Login</h2>
</div>
<div class='form-body'>
<div class='form-row'>
<div class='input-container'>
<i class='fas fa-user'></i>
<?php $attributes = [
'type' => 'text',
'name' => 'username',
'class' => 'input-field',
'id' => 'username',
'placeholder' => 'Username',
'required' => TRUE,
]; ?>
<?= form_input($attributes); ?>
</div>
</div>
<div class='form-row'>
<div class='input-container'>
<i class='fas fa-lock'></i>
<?php $attributes = [
'type' => 'password',
'name' => 'password',
'class' => 'input-field',
'placeholder' => 'Password',
'required' => TRUE,
]; ?>
<?= form_input($attributes); ?>
</div`>
</div>
</div>
<div class='captcha-container'>
<div class='g-recaptcha' data-sitekey='<?= env('recaptcha2_sitekey'); ?>'></div>
</div>
<div class='form-footer'>
<?php $submit = [
'name' => 'loginSubmit',
'value' => 'Login',
'class' => 'submit-btn',
];?>
<?= form_submit($submit); ?>
</div>
<h4 style='text-align: center'>Not a member yet? Register
<a href= <?= site_url('users/register'); ?> title = 'Register'> HERE</a>
</h4>
<?= form_close(); ?>
</div>
It was a stupid mistake. Someone on the codeigniter forum answered my question here: CodeIgniter Forum
basically in my constructor I needed $this->userModel = new UserModel(); instead of $userModel = new UserModel();.

Yii2: Assign sum of textfields to another field in form

Im new to Yii and I'm trying to assign the sum of 3 different fields in my _form.php into a total field. I've tried assigning it directly in the controller but the total field stays null. I'm basically trying to achieve this:
$model->cuerdas= $model->propia + $model->usofructo + $model->arrendada;
This is the actionCreate code of the Controller where I tried making the assignment:
public function actionCreate()
{
$model = new AsdaPa0025();
$modelosfacilidades = [new FacilidadesARealizar0025()];
if ($model->load(Yii::$app->request->post())) {
$model->file = UploadedFile::getInstance($model, 'file');
$modelosfacilidades = Model::createMultiple(FacilidadesARealizar0025::classname());
Model::loadMultiple($modelosfacilidades, Yii::$app->request->post());
//valida los modelos
$valid = $model->validate();
$valid = Model::validateMultiple($modelosfacilidades) && $valid;
if ($valid) {
$transaction = \Yii::$app->db->beginTransaction();
try {
if ($flag = $model->save(false)) {
foreach ($modelosfacilidades as $modelofacilidades) {
//Aqui le digo al controlador que id_0025 es igual al id de la instancia de la forma 0025
$modelofacilidades->id_0025 = $model->id_asda_pa_0025;
if (! ($flag = $modelofacilidades->save(false))) {
$transaction->rollBack();
break;
}
}
}
if ($flag) {
$transaction->commit();
$model->cuerdas= $model->propia + $model->usofructo + $model->arrendada;
$model->file->saveAs('uploads/' . $model->file->baseName . '.' . $model->file->extension);
return $this->redirect(['view', 'id' => $model->id_asda_pa_0025]);
}
} catch (Exception $e) {
$transaction->rollBack();
}
}
// $model->file = 'uploads/' . $model->imageFile->baseName . '.' . $model->imageFile->extension;
// if ($model->save()) {
// $model->file->saveAs('uploads/' . $model->file->baseName . '.' . $model->file->extension);
// return $this->redirect(['view', 'id' => $model->id_asda_pa_0025]);
}
else{
// return $this->redirect(['view', 'id' => $model->id_asda_pa_0025]);
return $this->render('create', [
'model' => $model,
'modelosfacilidades' => (empty($modelosfacilidades)) ? [new FacilidadesARealizar0025] : $modelosfacilidades
]);
}
}
I also tried calling this function from model in the controller instead of the manual assignment but I get a using this->() when not in object context error
/**
* #return \yii\db\ActiveQuery
*/
public static function getSuma()
{
return $this->find()->sum('propia + arrendada + usofructo');
}
This is my _form.php where the fields are:
<div class="col-sm-6">
Cuerdas
<?= $form->field($model, 'propia')->textInput()->label('7.Propia') ?>
<?= $form->field($model, 'arrendada')->textInput()->label('8.Arrendada') ?>
<?= $form->field($model, 'usofructo')->textInput()->label('9.Usufructo') ?>
<?= $form->field($model, 'cuerdas')->textInput(['readOnly'=> true])->label('10. Total Cuerdas')?>
</div>
I turned the cuerdas field input as readonly since it is going to be the one that will receive the sum of the other 3 values.
I would appreciate any help on how would the correct approach be to achieve this.
Assuming you have properly assigned the value in form once your model is loaded the values you have assigned are available so
if ($model->load(Yii::$app->request->post())) {
$model->cuerdas= $model->propia + $model->usofructo + $model->arrendada;
......
should work

Silverstripe group result by specific subject

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.

How to create customer information form in home page and form data store in database in opencart

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.

Zend View Helper function URL redirects to wrong controller

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