JOOMLA: Call to a member function getFieldset() on a non-object - php

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

Related

Need A Value of id of url inside a box

i am a newbie having difficulty in this. i did not getting a value of ID In A box for Update Inside A Box.
update code
<?php
require_once (__DIR__ . '/../../config.php');
require_once($CFG->dirroot.'/local/message/classes/form/edit.php');
global $DB;
$PAGE->set_url(new moodle_url('/local/message/update.php'));
$PAGE->set_context(\context_system::instance());
$PAGE->set_title('Edit');
//here display form
$mform=new edit();
$table='local_message';
$id=required_param('id', PARAM_INT);
$info=$DB->get_records($table,array('id' => $id));
if ($mform->is_cancelled()) {
print_r("1");
redirect($CFG->wwwroot.'/local/message/manage.php', 'You Cancelled The Form');
} else if ($fromform = $mform->get_data()) {
print_r("2");
$record = new stdClass();
$record->id=$id;
$record->messagetext = $fromform->messagetext;
$record->messagetype = $fromform->messagetype;
$DB->update_record($table, $record);
redirect($CFG->wwwroot . '/local/message/manage.php', 'you created a message with a title ' . $fromform->messagetext);
}
echo $OUTPUT->header();
$mform->display();
echo $OUTPUT->footer();
Form/moodle/Code
<?php
require_once("$CFG->libdir/formslib.php");
class edit extends moodleform {
public function definition() {
global $CFG;
$mform = $this->_form; // Don't forget the underscore!
$mform->addElement('text', 'id');
$mform->setType('id', PARAM_INT);
$mform->addElement('text', 'messagetext', get_string('message_text', 'local_message')); // Add elements to your form
$mform->setType('messagetext', PARAM_NOTAGS); //Set type of element
$mform->setDefault('messagetext', get_string('enter_message', 'local_message')); //Default value
$choices = array();
$choices['0'] = \core\output\notification::NOTIFY_WARNING;
$choices['1'] = \core\output\notification::NOTIFY_SUCCESS;
$choices['2'] = \core\output\notification::NOTIFY_ERROR;
$[enter image description here][1]choices['3'] = \core\output\notification::NOTIFY_INFO;
$mform->addElement('select', 'messagetype', get_string('message_type', 'local_message'), $choices);
$mform->setDefault('messagetype', '3');
$this->add_action_buttons();
}
//Custom validation should be added here
function validation($data, $files) {
return array();
}
}
You need to pass the id to the form before displaying the form
$mform->set_data($info);
$mform->display();
Also, you should use the single get_record function not the multiple get_records function
$info = $DB->get_record($table, array('id' => $id));
Also, you might want to use the hidden element for the id
$mform->addElement('hidden', 'id');

Retrieve data from zend form

I'm a Zend Framework newbie and I'm trying to retrieve some values to update the database. I have the following code in the controller. Populating the form works just fine, as does updating the db with some hard-coded values. My problem lies in trying to retrieve an updated value from the form, see the $first_name variable. It gives me a fatal error.
My question: How do I retrieve an updated value from the form?
public function editAction() {
$view = $this->view;
//get the application
$application_id = $this->getRequest()->getParam('id');
$application = $this->getApplication($application_id);
//get the applicant
$applicant_id = $application->applicant_id;
$applicant = $this->getApplicant($applicant_id);
if ($this->getRequest()->isPost()) {
if ($this->getRequest()->getPost('Save')) {
$applicants_table = new Applicants();
$first_name = $form->getValue('applicant_first_name');
$update_data = array ('first_name' => 'NewFirstName',
'last_name' => 'NewLastName');
$where = array('applicant_id = ?' => 16);
$applicants_table->update($update_data, $where);
}
$url = 'applications/list';
$this->_redirect($url);
} else { //populate the form
//applicant data
$applicant_data = array();
$applicant_array = $applicant->toArray();
foreach ($applicant_array as $field => $value) {
$applicant_data['applicant_'.$field] = $value;
}
$form = new FormEdit();
$form->populate($applicant_data);
$this->view->form = $form;
}
}
First off, your example has a problem here:
$first_name = $form->getValue('applicant_first_name');
...your $form isn't created yet, thus the fatal error; you are calling getValue() on a non-object.
Once you get that squared away, you can populate the form with posted data by calling the isValid method on the $form with request data. Here's a quick example:
// setup $application_data
$form = new FormEdit();
$form->populate($applicant_data);
if ($this->getRequest()->isPost()) {
if ($form->isValid($this->getRequest()->getPost())) {
$first_name = $form->getValue('applicant_first_name');
// save data to the database ...
}
}

How To render Silex Forms in Smarty Template?

I just stuck at a point.
To render Forms in Smarty Template.
Well, smarty is well configured in my silex project.
here is the Code in my controller class.
$loginForm = $app['form.factory']
->createBuilder(new Form\UserLogin())
->getForm();
$app['smarty']->assign('loginForm', $loginForm->createView());
return $app['smarty']->render('login.tpl');
Here is the code in my tpl file
{block name="headline"}
<h1>User Login</h1>
{/block}
{block name="content"}
<div>
{form_widget(loginForm)}
</div>
{/block}
And i am getting this exception.
SmartyCompilerException:
Syntax Error in template "/home/Symfony/demo/App/View/login.tpl" on line 8
"{form_widget(loginForm)}" unknown function "form_widget"
Edit:
Ok i found the issue but not getting the solution.
Following is SmartyServiceProvider Class.
<?php
namespace App\ServiceProvider;
use Silex\Application;
use \Symfony\Component\HttpFoundation\Request;
use Silex\ServiceProviderInterface;
use App\Classes\Smarty;
use NoiseLabs\Bundle\SmartyBundle\Form\SmartyRendererInterface;
use \NoiseLabs\Bundle\SmartyBundle\Extension\AbstractExtension;
use \NoiseLabs\Bundle\SmartyBundle\Extension\FormExtension;
use \NoiseLabs\Bundle\SmartyBundle\Form;
class SmartyServiceProvider implements ServiceProviderInterface
{
public function register(Application $app)
{
$app['smarty.auto-render'] = true;
$app['smarty.extension'] = $app->protect(
function (AbstractExtension $extension, Smarty $smarty = null) use ($app) {
if ($smarty == null) {
$smarty = $app['smarty'];
}
/** #var $plugin \NoiseLabs\Bundle\SmartyBundle\Extension\Plugin\AbstractPlugin */
/** #var $filter \NoiseLabs\Bundle\SmartyBundle\Extension\Filter\AbstractFilter */
foreach ($extension->getPlugins() as $plugin) {
//print $plugin->getName() . " | " . $plugin->getType() . "<br>";
$smarty->registerPlugin($plugin->getType(), $plugin->getName(), $plugin->getCallback());
}
foreach ($extension->getFilters() as $filter) {
$smarty->registerFilter($filter->getType(), $filter->getCallback());
}
}
);
$app['smarty.extensions'] = $app->protect(
function (array $extensions, Smarty $smarty = null) use ($app) {
foreach ($extensions as $extension) {
$app['smarty.extension']($extension, $smarty);
}
}
);
$app['smarty'] = $app->share(
function () use ($app) {
$app['directory.smarty.plugins'] = $app['directory.root.app'] . '/Classes/Smarty/Plugins';
$smarty = isset($app['smarty.instance']) ? $app['smarty.instance'] : new Smarty(
$app,
isset($app['smarty.primary.template.dir'])
? $app['smarty.primary.template.dir']
: $app['directory.root.view'],
false
);
if (isset($app["smarty.options"]) && is_array($app["smarty.options"])) {
foreach ($app["smarty.options"] as $smartyOptionName => $smartyOptionValue) {
$smarty->$smartyOptionName = $smartyOptionValue;
}
}
$smarty->assign("app", $app);
if (isset($app['smarty.configure'])) {
$app['smarty.configure']($smarty);
}
$extensions = [];
//$extensions[] = new \NoiseLabs\Bundle\SmartyBundle\Extension\FormExtension();
$extensions[] = new \NoiseLabs\Bundle\SmartyBundle\Extension\RoutingExtension($app['url_generator']);
$extensions[] = new \App\Classes\Smarty\HookExtension();
$app['smarty.extensions']($extensions, $smarty);
return $smarty;
}
);
}
public function boot(Application $app)
{
}
}
Here in that class i have loaded extensions of SmartyBundle here.
Here I'll have to load FormExtensions.
$extensions = [];
$extensions[] = new \NoiseLabs\Bundle\SmartyBundle\Extension\FormExtension('Don't know how to get SmartyRendererInterface instance here');
$extensions[] = new \NoiseLabs\Bundle\SmartyBundle\Extension\RoutingExtension($app['url_generator']);
$extensions[] = new \App\Classes\Smarty\HookExtension();
$app['smarty.extensions']($extensions, $smarty);
The correct syntax for the Form Widget is:
{form_widget form=$loginForm}
From your example it's not clear the out from $loginForm->createView() and you're lacking the form tags ( ie )that normally surround the Form widget. If the createView includes these you make be not need the form widget and just need to output the entire form HTML as:
{$loginForm}

Code igniter Themes' library.

I need 3 different templates for my Codeigniter application. I had read about Themes' library. But still I didn't get any idea about how to add a template to Codeignier ..
I got about how to involke template in Controller .
Please help
I'm using this template library, is really simple and works well for me.
application/libraries/Template.php
<?php
class Template {
var $template_data = array();
var $use_template = '';
/**
* Set variable for using in the template
*/
function set($name, $value)
{
$this->template_data[$name] = $value;
}
/**
* Set template name
*/
function set_template($name)
{
$this->use_template = $name;
}
/**
* Load view
*/
function load($view = '' , $view_data = array(), $template = '', $return = FALSE)
{
$this->CI =& get_instance();
if (empty($template)) {
$template = $this->CI->config->item('template_master');
}
if (!empty($this->use_template)) {
$template = $this->use_template;
}
$this->set($this->CI->config->item('data_container'), $this->CI->load->view($view, array_merge($view_data, array ('template' => $this->template_data)), true));
return $this->CI->load->view($this->CI->config->item('template_folder') . '/' . $template, $this->template_data, $return);
}
}
application/config/template.php
<?php
$config['template_master'] = 'main';
$config['template_folder'] = 'templates';
$config['data_container'] = 'content';
application/views/templates/main.php
Header<br />
<?php echo $content; ?></br>
Footer
application/controllers/welcome.php
<?php
class Welcome extends CI_Controller
{
public function index()
{
$this->load->config('template');
$this->load->library('template');
$this->template->load('welcome', array('view' => 'data'));
}
}
I usually put the config/library files on autoload, and you can use anytime $this->template->set_template('other_template'); to use another one :)
Hope it helps.
I've used the following setup in a CodeIgniter project:
The different templates along with stylesheets and images are in the following folder:
/templates/1/header.php
/templates/1/footer.php
/templates/1/images/*
/templates/1/style/*
/templates/2/header.php
/templates/2/footer.php
/templates/2/images/*
/templates/2/style/*
In your Controllers determine which template you want to load and pass the path to that template as a variable ( templatepath in this case ) to your View files. Inside the view files you do the following:
<?php include($templatepath.'/header.php'); ?>
at the top and
<?php include($templatepath.'/footer.php'); ?>
at the bottom.

PHP including external files which use class fields from base file

Let's say I have a class...
class A {
private $action;
private $includes;
public function __construct($action, $file) {
//assign fields
}
public function includeFile()
include_once($this->file);
}
$a = new A('foo.process.php', 'somefile.php');
$a->includeFile();
As you can see, includeFile() calls the include from within the function, therefore once the external file is included, it should technically be inside of the function from my understanding.
After I've done that, let's look at the file included, which is somefile.php, which calls the field like so.
<form action=<?=$this->action;?> method="post" name="someForm">
<!--moar markup here-->
</form>
When I try to do this, I receive an error. Yet, in a CMS like Joomla I see this accomplished all the time. How is this possible?
Update
Here's the error I get.
Fatal error: Using $this when not in object context in /var/www/form/form.process.php on line 8
Update 2
Here's my code:
class EditForm implements ISave{
private $formName;
private $adData;
private $photoData;
private $urlData;
private $includes;
public function __construct(AdData $adData, PhotoData $photoData, UrlData $urlData, $includes) {
$this->formName = 'pageOne';
$this->adData = $adData;
$this->photoData = $photoData;
$this->urlData = $urlData;
$this->includes = $includes;
}
public function saveData() {
$this->adData->saveData();
$this->photoData->saveData();
}
public function includeFiles() {
if (is_array($this->includes)) {
foreach($this->includes as $file) {
include_once($file);
}
} else {
include_once($this->includes);
}
}
public function populateCategories($parent) {
$categories = $this->getCategories($parent);
$this->printCategories($categories);
}
public function populateCountries() {
$countries = $this->getCountries();
$this->printCountries($countries);
}
public function populateSubCategories() {
//TODO
}
private function getCategories($parent) {
$db = patentionConnect();
$query =
"SELECT * FROM `jos_adsmanager_categories`
WHERE `parent` = :parent";
$result = $db->fetchAll(
$query,
array(
new PQO(':parent', $parent)
)
);
return $result;
}
private function getCountries() {
$db = patentionConnect();
$query =
"SELECT `fieldtitle` FROM `jos_adsmanager_field_values`
WHERE fieldid = :id";
$result = $db->fetchAll(
$query,
array(
new PQO(':id', 29)
)
);
return $result;
}
private function printCountries(array $countries) {
foreach($countries as $row) {
?>
<option value=<?=$row['fieldtitle'];?> >
<?=$row['fieldtitle'];?>
</option>
<?php
}
}
private function printCategories(array $categories) {
foreach($categories as $key => $row){
?>
<option value=<?=$row['id'];?>>
<?=$row['name'];?>
</option>
<?php
}
}
}
And the include call (which exists in the same file):
$template = new EditForm(
new AdData(),
new PhotoData(),
new UrlData($Itemid),
array(
'form.php',
'form.process.php'
)
);
$template->includeFiles();
And the main file which is included...
if ($this->formName == "pageOne") {
$this->adData->addData('category', $_POST['category']);
$this->adData->addData('subcategory', $_POST['subcategory']);
} else if ($this->formName == "pageTwo") {
$this->adData->addData('ad_Website', $_POST['ad_Website']);
$this->adData->addData('ad_Patent', $_POST['ad_Patent']);
$this->adData->addData('ad_Address', $_POST['ad_Address']);
$this->adData->addData('email', $_POST['email']);
$this->adData->addData('hide_email', $_POST['hide_email']);
$this->adData->addData('ad_phone', $_POST['ad_phone']);
$this->adData->addData('ad_Protection', $_POST['ad_Protection']);
$this->adData->addData('ad_Number', $_POST['ad_Number']);
$this->adData->addData('ad_Country', $_POST['ad_Country']);
$this->adData->addData('ad_issuedate', $_POST['issuedate'] . '/' . $_POST['issuemonth'] . '/' . $_POST['issueyear']);
} else if ($this->formName == "pageThree") {
$this->adData->addData('name', $_POST['name']);
$this->adData->addData('ad_Background', $_POST['ad_Background']);
$this->adData->addData('ad_opeartion', $_POST['ad_operation']);
$this->adData->addData('ad_advlimit', $_POST['ad_advlimit']);
$this->adData->addData('ad_status', $_POST['ad_status']);
$this->adData->addData('ad_addinfo', $_POST['ad_addinfo']);
$this->adData->addData('ad_description', $_POST['ad_description']);
$this->adData->addData('tags', $_POST['tags']);
$this->adData->addData('videolink', $_POST['videolink']);
} else if ($this->formName == "pageFour") {
foreach($_POST['jos_photos'] as $photo) {
$this->photoData->addData(
array(
'title' => $photo['title'],
'url' => $photo['url'],
'ad_id' => $this->photoData->__get('ad_id'),
'userid' => $this->photoData->__get('userid')
)
);
}
}
Update
Strange: while the error itself hadn't been quite related to what the problem was, I found that it was simply an undefined field which I hadn't implemented.
Consider this thread solved. To those who replied, I certainly appreciate it regardless.
This should work. Are you sure you're doing the include from a non-static method that's part of the class (class A in your example)? Can you post the exact code you're using?
Edit: As general advice for problems like this, see if you can trim down the code so the problem is reproducible in a short, simple example that anyone could easily copy/paste to reproduce the exact error. The majority of the time, you'll figure out the answer yourself in the process of trying to simplify. And if you don't, it will make it much easier for others to help you debug.

Categories