I'm making a simple MVC component for joomla following the hello world tutorial for the most part, with some some text fields and an image.
The text fields save but the "file" field does not, any ideas?
**Controller:**
<?php
// No direct access to this file
defined('_JEXEC') or die('Restricted access');
// import Joomla controllerform library
jimport('joomla.application.component.controllerform');
/**
* MJob Controller
*/
class MJobsControllerMJob extends JControllerForm
{
}
**Model:**
<?php
// No direct access to this file
defined('_JEXEC') or die('Restricted access');
// import Joomla modelform library
jimport('joomla.application.component.modeladmin');
class MJobsModelMJob extends JModelAdmin
{
public function getTable($type = 'MJob', $prefix = 'MJobsTable', $config = array())
{
return JTable::getInstance($type, $prefix, $config);
}
public function getForm($data = array(), $loadData = true)
{
// Get the form.
$form = $this->loadForm('com_mjobs.mjob', 'mjob', array('control' => 'jform', 'load_data' => $loadData));
if (empty($form))
{
return false;
}
return $form;
}
protected function loadFormData()
{
// Check the session for previously entered form data.
$data = JFactory::getApplication()->getUserState('com_mjobs.edit.mjob.data', array());
if (empty($data))
{
$data = $this->getItem();
}
return $data;
}
}
**view.html.php:**
<?php
// No direct access to this file
defined('_JEXEC') or die('Restricted access');
// import Joomla view library
jimport('joomla.application.component.view');
class MJobsViewMJob extends JView
{
public function display($tpl = null)
{
// get the Data
$form = $this->get('Form');
$item = $this->get('Item');
// Check for errors.
if (count($errors = $this->get('Errors')))
{
JError::raiseError(500, implode('<br />', $errors));
return false;
}
// Assign the Data
$this->form = $form;
$this->item = $item;
// Set the toolbar
$this->addToolBar();
// Display the template
parent::display($tpl);
}
protected function addToolBar()
{
JRequest::setVar('hidemainmenu', true);
$isNew = ($this->item->id == 0);
JToolBarHelper::title($isNew ? JText::_('COM_MJOBS_MANAGER_MJOB_NEW') : JText::_('COM_MJOBS_MANAGER_MJOB_EDIT'));
JToolBarHelper::apply('mjob.apply');
JToolBarHelper::save('mjob.save');
JToolBarHelper::save2new('mjob.save2new');
JToolBarHelper::cancel('mjob.cancel', $isNew ? 'JTOOLBAR_CANCEL' : 'JTOOLBAR_CLOSE');
}
}
**VIEW (tmpl/edit.php):**
<?php
// No direct access
defined('_JEXEC') or die('Restricted access');
JHtml::_('behavior.tooltip');
echo "<b>MJOB EDIT START</b><br>";
?>
<form action="<?php echo JRoute::_('index.php?option=com_mjobs&layout=edit&id='.(int) $this->item->id); ?>"
method="post" enctype="multipart/form-data" name="adminForm" id="mjob-form">
<fieldset class="adminform">
<legend><?php echo JText::_( 'COM_MJOBS_MJOB_DETAILS' ); ?></legend>
<ul class="adminformlist">
<?php foreach($this->form->getFieldset('details') as $field): ?>
<li><?php echo $field->label;echo $field->input;?></li>
<?php endforeach; ?>
</ul>
</fieldset>
<div>
<input type="hidden" name="task" value="mjob.edit" />
<?php echo JHtml::_('form.token'); ?>
</div>
</form>
I'm guessing you're using Joomla! 2.5 based on the code provided.
So to retrieve a file that's been uploaded you will need to do something like:
$jFileInput = new JInput($_FILES);
$theFile = $jFileInput->get('jform',array(),'array');
// If there is no uploaded file, we have a problem...
if (!is_array($theFile)) {
JError::raiseWarning('', 'No file was selected.');
return false;
}
// Build the paths for our file to move to the components 'upload' directory
$theFileName = $theFile['name']['tablefile'];
$tmp_src = $theFile['tmp_name']['tablefile'];
$tmp_dest = JPATH_COMPONENT_ADMINISTRATOR . '/uploads/' . $theFileName;
$this->dataFile = $theFileName;
// Move uploaded file
jimport('joomla.filesystem.file');
$uploaded = JFile::upload($tmp_src, $tmp_dest);
// $uploaded contains boolean indicating success or failure
// $tmp_dest will contain final location of file if successful.
Also make sure in your html form you have
enctype="multipart/form-data"
enabled otherwise you won't receive any files in php.
Related
I have 2 classes one is Language.php and the second is Landing.php.
The language class contains :
<?php
namespace App\Core;
class Language {
function getLanguage($language = null)
{
$lang = $this->setLanguage($language);
if(file_exists(LANGUAGE_DIR ."/".$lang.".php"))
{
ob_start();
include LANGUAGE_DIR."/".$lang.".php"; //INCLUDE EN.PHP
return ob_get_clean();
} else {
ob_start();
include LANGUAGE_DIR."/en.php";
return ob_get_clean();
}
}
}
The landing class contains:
<?php
namespace App\Models\Landing;
use App\Core\Database;
use App\Core\Language;
class Landing extends Database
{
public function reportBug(string $language, int $video, string $sender, string $commentaire)
{
$lang = new Language;
$lang->getLanguage($language); //THIS DOESN'T WORK
//include LANGUAGE_DIR."/".$language.".php"; //UNCOMMENT THIS LINE EVERYTHING WORKS
//Save the comment
$rowCount = $this->insert("INSERT INTO comments(video, message)VALUES(?, ?)", array($video, $commentaire), false);
if($rowCount == 1){
return '1'; //Success
}else {
return '<div class="alert alert-danger">'. $commentNotSent .'</div>'; //$commentNotSent throw error
}
}
}
I have also this file en.php:
<?php
$commentNotSent = "Comment not sent";
The problem is that I cannot display $commentNotSent variable. Can you help me please?
I'm loading the main view within the controller home as following:
class Home
{
public static function login()
{
Views::load('frontend/index', ['view' => 'account/login', 'name' => 'Stackoverflow']);
}
}
Now as you can see the view being loaded is frontend/index but I also say what is the view that must be loaded afterwards account/login.
So in the frontend/index.php file I have the following:
<!DOCTYPE html>
<html>
<head>
</head>
<body>
<?php Views::load($view); ?>
<?php echo $name; // prints 'stackoverflow' ?>
</body>
</html>
What happens is that I'm able to access the variable $name in the frontend/index file but not in the account/login file.
The account/login.php file contains:
<h2>Hello: <?php echo $name; // shows error saying 'Undefined variable: name' ?></h2>
The error just tells me that the variable is not being cached/stored.
Finally my view class has the following structure:
<?php
class Views
{
public static function load($file, $data = null)
{
if(file_exists(VIEWS_PATH . $file . '.php') == FALSE)
throw new Exception('View not found');
if($data != null)
extract($data, EXTR_SKIP);
ob_start();
require_once(VIEWS_PATH . $file . '.php');
$content = ob_get_contents();
ob_end_clean();
// prints the view
echo $content;
}
}
What can I do in order to allow the variables sent by controller to be cached/stored and called in multiple views?
I'm beginner in PHP and developing my own component for Joomla. I've replaced all the classes in HelloWorld example but yet I haven't change the names of views. If I try to open the specific message/record in the backend I get the error:
Fatal error: Call to a member function getFieldset() on a non-object in administrator/components/com_mycom/views/helloworld/tmpl/edit.php on line 12
Line 12: <?php foreach ($this->form->getFieldset('details') as $field) : ?>
The code of my administrator/components/com_mycom/models/fields/mycom.php:
<?php
defined('_JEXEC') or die;
jimport('joomla.form.helper');
JFormHelper::loadFieldClass('list');
class JFormFieldHelloWorld extends JFormFieldList
{
protected $type = 'Mycom';
protected function getOptions()
{
$db = JFactory::getDBO();
$query = $db->getQuery(true);
$query->select('h.id, h.header, h.parent')
->from('#__pages as h')
->select('c.title as category')
->leftJoin('#__categories AS c ON c.id = h.parent');
$db->setQuery($query);
$messages = $db->loadObjectList();
$options = array();
if ($messages)
{
foreach ($messages as $message)
{
$options[] = JHtml::_('select.option', $message->id,
$message->header . ($message->parent ? ' (' . $message->category . ')' : '')
);
}
}
$options = array_merge(parent::getOptions(), $options);
return $options;
}
}
Joomla 3.4
There must be administrator/components/com_mycom/models/fields/helloworld.php as model/view for single record
When creating a form, form fields are specified in an XML file in models/forms/helloworld.xml form fields are specified in a fieldset. To get the form fields in view page, we can use any one of the following method.
$this->form = $this->get('Form'); // use in view.html.php file where we store data to be used in view file (edit.php)
in the model file of helloworld.php define the function
public function getForm($data = array(), $loadData = true) {
// Initialise variables.
$app = JFactory::getApplication();
// Get the form.
$form = $this->loadForm('com_helloworld.helloworld', 'helloworld', array('control' => 'jform', 'load_data' => $loadData));
if (empty($form)) {
return false;
}
return $form;
}
in the view edit.php file
<?php echo $this->form->getLabel('name'); ?> // label name
<?php echo $this->form->getInput('name'); ?> // input text fields
The other method is
$fieldset = $this->form->getFieldset('fieldset_name'); // name of the fieldset in xml file.
this returns an array.
https://docs.joomla.org/API16:JForm/getFieldset
I'm new to Kohana and I'm following this excellent tutorial. I am getting this cryptic error message
ErrorException [ 8 ]: Array to string conversion ~
SYSPATH\classes\Kohana\Log\Writer.php [ 81 ]
after trying to load this url
http://localhost/kohana-blog/index.php/article/new
The problem seems to be originating from my Model_Article() because I get this error with only this line of code in it
public function action_new()
{
$article = new Model_Article();
/*
$view = new View('article/edit');
$view->set("article", $article);
$this->response->body($view);
*/
}
I uncommented database and orm in application/bootstrap.php as suggested by the author.
Here is application/classes/Controller/Article.php:
<?php defined('SYSPATH') or die('No direct script access.');
class Controller_Article extends Controller {
public function action_index()
{
$view = new View('article/index');
$this->response->body($view);
}
// loads the new article form
public function action_new()
{
$article = new Model_Article();
$view = new View('article/edit');
$view->set("article", $article);
$this->response->body($view);
}
// save the article
public function action_post()
{
$article_id = $this->request->param('id');
$article = new Model_Article($article_id);
// Populate $article object form
$article->values($_POST);
// Saves article to database
$article->save();
// Redirects to article page after saving
$this->request->redirect('index.php/article');
}
}
Here is application/views/article/edit.php
<?php defined('SYSPATH') or die('No direct script access.'); ?>
<h1>Create new article</h1>
<?php echo Form::open('article/post/'.$article->id); ?>
<?php echo Form::label("title", "Title"); ?>
<br />
<?php echo Form::input("title", $article->title); ?>
<br />
<br />
<?php echo Form::label("content", "Content"); ?>
<br />
<?php echo Form::textarea("content", $article->content); ?>
<br />
<br />
<?php echo Form::submit("submit", "Submit"); ?>
<?php echo Form::close(); ?>
And here is application/classes/Model/article.php
<?php defined ('SYSPATH') or die('No direct script access');
class Model_Article extends ORM {
}
This is a known issue when running PHP 5.4.12 and beyond. It has been fixed in 3.3.1.
Here is the class:
functions.php
class buildPage {
public function Set($var,$val){
$this->set->$var = $val;
}
function Body(){
ob_start();
include('pages/'.$this->set->pageFile);
$page = ob_get_contents();
ob_end_clean();
return $page;
}
function Out(){
echo $this->Body();
}
}
So here is the main (index) page of the script.
index.php
include_once('include/functions.php');
$page = new buildPage();
$page->Set('pageTitle','Old Title');
$page->Set('pageFile','about.php');
$page->Out();
Now as you can see, it includes about.php file through class, actually inside the class.
And now, I want to access the same buildPage() class to change the page title.
about.php
<?php
$this->Set('pageTitle','New Title');
echo '<h1>About Us</h1>';
?>
But unfortunately, nothing happens.
Please be kind to take few minutes to give me some help!
OK. I've managed to fix the problem myself.
Changed function Body() and Out() as follows :
function Body(){
$pageFile = $this->Get('pageFile');
if(empty($pageFile)){
$pageFile = 'home.php';
}
$page_path = 'pages/'.$pageFile;
ob_start();
include($page_path);
if(!empty($page_set_arr) && is_array($page_set_arr)){
foreach($page_set_arr AS $k=>$v){
$this->Set($k,$v);
}
}
$page = ob_get_clean();
return $page;
}
function Out(){
$body = $this->Body();
echo $this->Header();
echo $body;
echo $this->Footer();
}
And then changed the file about.php as follows :
<?php
$page_set_arr = array(
'pageTitle' => 'About Us'
);
?>
<h1>About Us</h1>