Добрый день!
Мне нужно написать свой компонент, но т.к. я не сильно шарю во всей системе MVC, решил воспользоваться генерацией начального каркаса компонента через Joomla Component Creator. Я раньше так делал уже и было все просто, в моделях определял переменные, а в видах уже выводил эти переменные как надо. Но сейчас совсем не так просто генерируется компонент, слишком, ну очень слишком много информации начальной....
Вот какие файлы я имею:
\controllers\office.php
\controllers\officeform.php
\controllers\offices.php
\models\office.php
\models\officeform.php
\models\offices.php
\views\office\
\views\officeform\
\views\offices\
хотя мне нужен был только одна модель "office", остальные сами создаются, на разных генераторах пробовал...
Пояните чуточку, зачем остальные файлы нужны и где в них что прописывать свое можно?
Помогите мне с простым примером, пожалуйста. Например, чтения из базы какой-нить данной и вывод ее в шаблон вида..\controllers\office.php
<?php
// No direct access
defined('_JEXEC') or die;
require_once JPATH_COMPONENT.'/controller.php';
/**
* Office controller class.
*/
class BsControllerOffice extends BsController
{
/**
* Method to check out an item for editing and redirect to the edit form.
*
* @since 1.6
*/
public function edit()
{
$app = JFactory::getApplication();
// Get the previous edit id (if any) and the current edit id.
$previousId = (int) $app->getUserState('com_bs.edit.office.id');
$editId = JFactory::getApplication()->input->getInt('id', null, 'array');
// Set the user id for the user to edit in the session.
$app->setUserState('com_bs.edit.office.id', $editId);
// Get the model.
$model = $this->getModel('Office', 'BsModel');
// Check out the item
if ($editId) {
$model->checkout($editId);
}
// Check in the previous user.
if ($previousId) {
$model->checkin($previousId);
}
// Redirect to the edit screen.
$this->setRedirect(JRoute::_('index.php?option=com_bs&view=officeform&layout=edit', false));
}
/**
* Method to save a user's profile data.
*
* @return void
* @since 1.6
*/
public function save()
{
// Check for request forgeries.
JSession::checkToken() or jexit(JText::_('JINVALID_TOKEN'));
// Initialise variables.
$app = JFactory::getApplication();
$model = $this->getModel('Office', 'BsModel');
// Get the user data.
$data = JFactory::getApplication()->input->get('jform', array(), 'array');
// Validate the posted data.
$form = $model->getForm();
if (!$form) {
JError::raiseError(500, $model->getError());
return false;
}
// Validate the posted data.
$data = $model->validate($form, $data);
// Check for errors.
if ($data === false) {
// Get the validation messages.
$errors = $model->getErrors();
// Push up to three validation messages out to the user.
for ($i = 0, $n = count($errors); $i < $n && $i < 3; $i++) {
if ($errors[$i] instanceof Exception) {
$app->enqueueMessage($errors[$i]->getMessage(), 'warning');
} else {
$app->enqueueMessage($errors[$i], 'warning');
}
}
// Save the data in the session.
$app->setUserState('com_bs.edit.office.data', JRequest::getVar('jform'),array());
// Redirect back to the edit screen.
$id = (int) $app->getUserState('com_bs.edit.office.id');
$this->setRedirect(JRoute::_('index.php?option=com_bs&view=office&layout=edit&id='.$id, false));
return false;
}
// Attempt to save the data.
$return = $model->save($data);
// Check for errors.
if ($return === false) {
// Save the data in the session.
$app->setUserState('com_bs.edit.office.data', $data);
// Redirect back to the edit screen.
$id = (int)$app->getUserState('com_bs.edit.office.id');
$this->setMessage(JText::sprintf('Save failed', $model->getError()), 'warning');
$this->setRedirect(JRoute::_('index.php?option=com_bs&view=office&layout=edit&id='.$id, false));
return false;
}
// Check in the profile.
if ($return) {
$model->checkin($return);
}
// Clear the profile id from the session.
$app->setUserState('com_bs.edit.office.id', null);
// Redirect to the list screen.
$this->setMessage(JText::_('COM_BS_ITEM_SAVED_SUCCESSFULLY'));
$menu = & JSite::getMenu();
$item = $menu->getActive();
$this->setRedirect(JRoute::_($item->link, false));
// Flush the data from the session.
$app->setUserState('com_bs.edit.office.data', null);
}
function cancel() {
$menu = & JSite::getMenu();
$item = $menu->getActive();
$this->setRedirect(JRoute::_($item->link, false));
}
public function remove()
{
// Check for request forgeries.
JSession::checkToken() or jexit(JText::_('JINVALID_TOKEN'));
// Initialise variables.
$app = JFactory::getApplication();
$model = $this->getModel('Office', 'BsModel');
// Get the user data.
$data = JFactory::getApplication()->input->get('jform', array(), 'array');
// Validate the posted data.
$form = $model->getForm();
if (!$form) {
JError::raiseError(500, $model->getError());
return false;
}
// Validate the posted data.
$data = $model->validate($form, $data);
// Check for errors.
if ($data === false) {
// Get the validation messages.
$errors = $model->getErrors();
// Push up to three validation messages out to the user.
for ($i = 0, $n = count($errors); $i < $n && $i < 3; $i++) {
if ($errors[$i] instanceof Exception) {
$app->enqueueMessage($errors[$i]->getMessage(), 'warning');
} else {
$app->enqueueMessage($errors[$i], 'warning');
}
}
// Save the data in the session.
$app->setUserState('com_bs.edit.office.data', $data);
// Redirect back to the edit screen.
$id = (int) $app->getUserState('com_bs.edit.office.id');
$this->setRedirect(JRoute::_('index.php?option=com_bs&view=office&layout=edit&id='.$id, false));
return false;
}
// Attempt to save the data.
$return = $model->delete($data);
// Check for errors.
if ($return === false) {
// Save the data in the session.
$app->setUserState('com_bs.edit.office.data', $data);
// Redirect back to the edit screen.
$id = (int)$app->getUserState('com_bs.edit.office.id');
$this->setMessage(JText::sprintf('Delete failed', $model->getError()), 'warning');
$this->setRedirect(JRoute::_('index.php?option=com_bs&view=office&layout=edit&id='.$id, false));
return false;
}
// Check in the profile.
if ($return) {
$model->checkin($return);
}
// Clear the profile id from the session.
$app->setUserState('com_bs.edit.office.id', null);
// Redirect to the list screen.
$this->setMessage(JText::_('COM_BS_ITEM_DELETED_SUCCESSFULLY'));
$menu = & JSite::getMenu();
$item = $menu->getActive();
$this->setRedirect(JRoute::_($item->link, false));
// Flush the data from the session.
$app->setUserState('com_bs.edit.office.data', null);
}
}
\models\office.php
<?php
// No direct access.
defined('_JEXEC') or die;
jimport('joomla.application.component.modelform');
jimport('joomla.event.dispatcher');
/**
* Bs model.
*/
class BsModelOffice extends JModelForm
{
var $_item = null;
/**
* Method to auto-populate the model state.
*
* Note. Calling getState in this method will result in recursion.
*
* @since 1.6
*/
protected function populateState()
{
$app = JFactory::getApplication('com_bs');
// Load state from the request userState on edit or from the passed variable on default
if (JFactory::getApplication()->input->get('layout') == 'edit') {
$id = JFactory::getApplication()->getUserState('com_bs.edit.office.id');
} else {
$id = JFactory::getApplication()->input->get('id');
JFactory::getApplication()->setUserState('com_bs.edit.office.id', $id);
}
$this->setState('office.id', $id);
// Load the parameters.
$params = $app->getParams();
$params_array = $params->toArray();
if(isset($params_array['item_id'])){
$this->setState('office.id', $params_array['item_id']);
}
$this->setState('params', $params);
}
/**
* Method to get an ojbect.
*
* @param integer The id of the object to get.
*
* @return mixed Object on success, false on failure.
*/
public function &getData($id = null)
{
if ($this->_item === null)
{
$this->_item = false;
if (empty($id)) {
$id = $this->getState('office.id');
}
// Get a level row instance.
$table = $this->getTable();
// Attempt to load the row.
if ($table->load($id))
{
// Check published state.
if ($published = $this->getState('filter.published'))
{
if ($table->state != $published) {
return $this->_item;
}
}
// Convert the JTable to a clean JObject.
$properties = $table->getProperties(1);
$this->_item = JArrayHelper::toObject($properties, 'JObject');
} elseif ($error = $table->getError()) {
$this->setError($error);
}
}
return $this->_item;
}
public function getTable($type = 'Office', $prefix = 'BsTable', $config = array())
{
$this->addTablePath(JPATH_COMPONENT_ADMINISTRATOR.'/tables');
return JTable::getInstance($type, $prefix, $config);
}
/**
* Method to check in an item.
*
* @param integer The id of the row to check out.
* @return boolean True on success, false on failure.
* @since 1.6
*/
public function checkin($id = null)
{
// Get the id.
$id = (!empty($id))? $id : (int)$this->getState('office.id');
if ($id) {
// Initialise the table
$table = $this->getTable();
// Attempt to check the row in.
if (method_exists($table, 'checkin')) {
if (!$table->checkin($id)) {
$this->setError($table->getError());
return false;
}
}
}
return true;
}
/**
* Method to check out an item for editing.
*
* @param integer The id of the row to check out.
* @return boolean True on success, false on failure.
* @since 1.6
*/
public function checkout($id = null)
{
// Get the user id.
$id = (!empty($id))? $id : (int)$this->getState('office.id');
if ($id) {
// Initialise the table
$table = $this->getTable();
// Get the current user object.
$user = JFactory::getUser();
// Attempt to check the row out.
if (method_exists($table, 'checkout')) {
if (!$table->checkout($user->get('id'), $id)) {
$this->setError($table->getError());
return false;
}
}
}
return true;
}
/**
* Method to get the profile form.
*
* The base form is loaded from XML
*
* @param array $data An optional array of data for the form to interogate.
* @param boolean $loadData True if the form is to load its own data (default case), false if not.
* @return JForm A JForm object on success, false on failure
* @since 1.6
*/
public function getForm($data = array(), $loadData = true)
{
// Get the form.
$form = $this->loadForm('com_bs.office', 'office', array('control' => 'jform', 'load_data' => $loadData));
if (empty($form)) {
return false;
}
return $form;
}
/**
* Method to get the data that should be injected in the form.
*
* @return mixed The data for the form.
* @since 1.6
*/
protected function loadFormData()
{
$data = $this->getData();
return $data;
}
/**
* Method to save the form data.
*
* @param array The form data.
* @return mixed The user id on success, false on failure.
* @since 1.6
*/
public function save($data)
{
$id = (!empty($data['id']))? $data['id'] : (int)$this->getState('office.id');
$state = (!empty($data['state']))? 1 : 0;
$user = JFactory::getUser();
if($id) {
//Check the user can edit this item
$authorised = $user->authorise('core.edit', 'com_bs') || $authorised = $user->authorise('core.edit.own', 'com_bs');
if($user->authorise('core.edit.state', 'com_bs')!== true && $state == 1){ //The user cannot edit the state of the item.
$data['state'] = 0;
}
} else {
//Check the user can create new items in this section
$authorised = $user->authorise('core.create', 'com_bs');
if($user->authorise('core.edit.state', 'com_bs')!== true && $state == 1){ //The user cannot edit the state of the item.
$data['state'] = 0;
}
}
if ($authorised !== true) {
JError::raiseError(403, JText::_('JERROR_ALERTNOAUTHOR'));
return false;
}
$table = $this->getTable();
if ($table->save($data) === true) {
return $id;
} else {
return false;
}
}
function delete($data)
{
$id = (!empty($data['id']))? $data['id'] : (int)$this->getState('office.id');
if(JFactory::getUser()->authorise('core.delete', 'com_bs')!== true){
JError::raiseError(403, JText::_('JERROR_ALERTNOAUTHOR'));
return false;
}
$table = $this->getTable();
if ($table->delete($data['id']) === true) {
return $id;
} else {
return false;
}
return true;
}
function getCategoryName($id){
$db = JFactory::getDbo();
$query = $db->getQuery(true);
$query
->select('title')
->from('#__categories')
->where('id = ' . $id);
$db->setQuery($query);
return $db->loadObject();
}
}
\views\office\
defined('_JEXEC') or die;
jimport('joomla.application.component.view');
/**
* View to edit
*/
class BsViewOffice extends JView {
protected $state;
protected $item;
protected $form;
protected $params;
/**
* Display the view
*/
public function display($tpl = null) {
$app = JFactory::getApplication();
$user = JFactory::getUser();
$this->state = $this->get('State');
$this->params = $app->getParams('com_bs');
// Check for errors.
if (count($errors = $this->get('Errors'))) {
throw new Exception(implode("\n", $errors));
}
if($this->_layout == 'edit') {
$authorised = $user->authorise('core.create', 'com_bs');
if ($authorised !== true) {
throw new Exception(JText::_('JERROR_ALERTNOAUTHOR'));
}
}
$this->_prepareDocument();
parent::display($tpl);
}
/**
* Prepares the document
*/
protected function _prepareDocument()
{
$app = JFactory::getApplication();
$menus = $app->getMenu();
$title = null;
// Because the application sets a default page title,
// we need to get it from the menu item itself
$menu = $menus->getActive();
if($menu)
{
$this->params->def('page_heading', $this->params->get('page_title', $menu->title));
} else {
$this->params->def('page_heading', JText::_('com_bs_DEFAULT_PAGE_TITLE'));
}
$title = $this->params->get('page_title', '');
if (empty($title)) {
$title = $app->getCfg('sitename');
}
elseif ($app->getCfg('sitename_pagetitles', 0) == 1) {
$title = JText::sprintf('JPAGETITLE', $app->getCfg('sitename'), $title);
}
elseif ($app->getCfg('sitename_pagetitles', 0) == 2) {
$title = JText::sprintf('JPAGETITLE', $title, $app->getCfg('sitename'));
}
$this->document->setTitle($title);
if ($this->params->get('menu-meta_description'))
{
$this->document->setDescription($this->params->get('menu-meta_description'));
}
if ($this->params->get('menu-meta_keywords'))
{
$this->document->setMetadata('keywords', $this->params->get('menu-meta_keywords'));
}
if ($this->params->get('robots'))
{
$this->document->setMetadata('robots', $this->params->get('robots'));
}
}
}
\views\office\tmpl\default.php
defined('_JEXEC') or die;
//Load admin language file
$lang = JFactory::getLanguage();
$lang->load('com_bs', JPATH_ADMINISTRATOR);
?>
<?php if ($this->item) : ?>
<div class="item_fields">
<ul class="fields_list">
</ul>
</div>
<?php
else:
echo JText::_('COM_BS_ITEM_NOT_LOADED');
endif;
?>