select box from a db table selected option - MVC

For Joomla! 1.5 Coding related discussions, please use: http://groups.google.com/group/joomla-dev-general
Locked
cheryl100
Joomla! Apprentice
Joomla! Apprentice
Posts: 30
Joined: Tue Mar 17, 2009 2:13 pm

select box from a db table selected option - MVC

Post by cheryl100 » Wed May 06, 2009 10:54 am

OK, I have:

$db =& JFactory::getDBO();
$query = 'SELECT id AS value, name as text FROM #__events_locations ORDER by name';
$locations[] = JHTML::_('select.option', '0', JText::_( 'Select Location' ));
$db->setQuery($query);
$locations = array_merge($locations, $db->loadObjectList());
$lists['listLocations'] = JHTML::_('select.genericlist', $locations, 'locid', 'class="inputbox" size="1"', 'value', 'text', $row->locid);

In view.html.php and in default.php I have:

echo $lists['listLocations'];

I am unsure as to where the list code should go, should it go in the controllers folder, or in the view.html.php file, is a select box part of the view or part of the controller? I think it is both. Anyway the code doesnt work. If I put :

$db =& JFactory::getDBO();
$query = 'SELECT `id`,`name` FROM #__events_locations';
$db->setQuery( $query );
$loclist = $db->loadObjectList();
echo JHTML::_('Select.genericlist',$loclist,"locid","","id","name",1);

in the views/default.php it works, but I know this isnt following the MVC, but, then how do I set the selected option of the select box using the joomla code, I could do this with PHP and HTML, but I'm trying, unsucessfully to follow the MVC model with joomla

User avatar
dam-man
Joomla! Exemplar
Joomla! Exemplar
Posts: 7961
Joined: Fri Sep 09, 2005 2:13 pm
Location: The Netherlands
Contact:

Re: select box from a db table selected option - MVC

Post by dam-man » Wed May 06, 2009 6:30 pm

It should be something like this:

Code: Select all

		$query = "SELECT makeid, makename FROM #__rdautos_makes WHERE published = 1"; 
		$db->setQuery($query);
	
		$javascript = " onchange=\"getModelList(this)\" ";
		
		$makelist[]	    = JHTML::_('select.option',  '0', JText::_( 'MAKE A SELECTION PLS' ), 'makeid', 'makename' );
		$makelist	    = array_merge( $makelist, $db->loadObjectList() );
		$lists['make']  = JHTML::_('select.genericlist',  $makelist, 'makeid', 'class="inputbox" size="1" '.$javascript, 'makeid',
		 'makename', intval($items->makeid));	
Robert Dam - Joomla Forum Moderator
Dutch Boards | Joomla Coding Boards | English Support Boards

vividearth
Joomla! Apprentice
Joomla! Apprentice
Posts: 26
Joined: Wed Apr 29, 2009 4:09 pm

Re: select box from a db table selected option - MVC

Post by vividearth » Thu May 07, 2009 9:41 am

Hi cheryl

What I have been doing for lookups is adding them to JHTML to push the logic out of the view layer. So what I do is create a JHTML helper class like this in a helpers/html folder:

Code: Select all

class MyComponentLookups
{
	function locations($name, $selected)
	{
		$db 	=& JFactory::getDBO();
		$query 	= 	'SELECT id AS value, name as text FROM #__events_locations ORDER by name';
		$db->setQuery($query);
		
		$options	= array();
		$options[]	= JHTML::_('select.option', '0', ' -'.JText::_('Select Location').'- ');
		$options 	= array_merge($options, $db->loadObjectList());
		
		// Return the select html:
		return JHTML::_('select.genericlist', $options, $name, null, 'value', 'text', $selected);
	}
}
In my components bootstrap file (eg mycomponent.php) load your custom helper class using:

Code: Select all

// Include custom JHTML helpers:
JHTML::addIncludePath( array( JPATH_COMPONENT.DS.'helpers'.DS.'html' ) );

Then to add a location look up use this in your view use:

Code: Select all

$lists['parent_id'] = JHTML::_('mycomponent.lookups.locations', 'jform[location_id]', $model->location_id);
and in your template:

Code: Select all

<?php echo $this->lists['location_id']; ?>

Keeps things quite clean - hope it helps.

cheryl100
Joomla! Apprentice
Joomla! Apprentice
Posts: 30
Joined: Tue Mar 17, 2009 2:13 pm

Re: select box from a db table selected option - MVC

Post by cheryl100 » Mon May 11, 2009 3:59 pm

Thanks very much for your prompt reply, I did manage to solve the problem myself by putting the list into an array, but I put the code into the views.html.php

// look up locations
$db1 =& JFactory::getDBO();
$query1 = 'SELECT #__events_locations.name AS loc FROM #__events_locations INNER JOIN #__events where #__events.locid = #__events_locations.id';
$db1->setQuery($query1);
$result1 = $db1->query();

$locs = array();
$num = 0;
while ($row = mysql_fetch_array($result1, MYSQL_BOTH)) {
$locs[$num] = $row[loc];
$num++;
}

$this->assignRef('locs',$locs);

and in the default file:
<?php echo $this->locs[$i]; ?>
It was difficult because I cant find a good book on Joomla coding and it all seems alot of trial and error. Are you saying that the code should go into
administration/components/my_component/helpers/html?
and be named my_helper.php?
where my_helper is any name you want to give the helper. I understand the other code. Please can you recomend a good up to date joomla 1.5+ programming book?
I am OK with PHP, mySQL, javascript and expert in actionscript 3
Thanks :-)

vividearth
Joomla! Apprentice
Joomla! Apprentice
Posts: 26
Joined: Wed Apr 29, 2009 4:09 pm

Re: select box from a db table selected option - MVC

Post by vividearth » Mon May 11, 2009 7:09 pm

The file location is correct and the file name can be whatever you want. In this bit of the code I posted:

Code: Select all

JHTML::_('mycomponent.lookups.locations', 'jform[location_id]', $model->location_id);
mycomponent is you component name, lookups is the file name and locations is the function name. So we wouold have a lookups.php file with a class named MyComponentLookups and a function called locations which returns the lookup.

One thing to look out for is that you cannot use the same file name as any of the Joomla core JHTML files. They are located at libraries\joomla\html\html. Joomla will search for just one file with the right name so using the same name will not work.

In terms of a book I used "Mastering Joomla 1.5" by James Kennard but would hesitate to recommend it. The examples use things like MyComponent and FooBar methods, which although ok in a forum or over a beer, I do not think are suitable for a technical book that people are paying money for - real world examples are far more educational!

I have been working with PHP and Joomla for a couple of weeks now and the best source's I have found are this forum, the code and JDump. Read through the core classes, dump out some variables and you will quickly start to see how it hangs together.

Start with these:

libraries\joomla\application\*.*
\libraries\joomla\base\object.php

Dave

cheryl100
Joomla! Apprentice
Joomla! Apprentice
Posts: 30
Joined: Tue Mar 17, 2009 2:13 pm

Re: select box from a db table selected option - MVC

Post by cheryl100 » Thu May 14, 2009 8:18 am

Thanks, I'll look at the libraires, but that seems like getting a bit teckie...
Can I just check the dir struc with you to make sure I'm heading in the right direction?
administrator/components/com_mycomponent
within there the following folders:
controllers
tables
models
views
and files:
config.php
install
uninstall
mycomponent.php
mycomponent.xml

in controllers folder there are the controllers for the various tables that you want to control and within them the classes
eg I have
locations
events
comments

models folder contain files for each table again and contain classes with functions that do search and pagination

tables contain the table definitions

views contain folders for each table as a single view and as a view for all the records, the view.html.php doesn't show the record/s, it contains a view class and states the variables that we want to assign, within each seperate table folder there is a tmpl folder which describes the layout.

I dont really understand the difference between the model and controller, I understand it in principle, the model does the thinking work and the contoller is what the user decides to do, so add and save are in the contoller, but surely publish and search should be in the controller as these are initiated by the user, also ther should be the 'doing' aspect of add and save in the contoller filess? Anyway I'm probably getting a bit too abstract, so I'll leave it at that. The example I started with was from the restaurants example from a joomla book, there are only 2, The one you mentioned and this one.

thanks again

cheryl

vividearth
Joomla! Apprentice
Joomla! Apprentice
Posts: 26
Joined: Wed Apr 29, 2009 4:09 pm

Re: select box from a db table selected option - MVC

Post by vividearth » Thu May 14, 2009 9:04 am

Hi Cheryl

You have the structure pretty much right there. A couple things I would say are:

Do not get into the trap of thinking that you need a controller for every model/table. For me controllers act as a way to divide your system into logical functional areas. They are the main entry point to your application and so need to hide the underlying structure for easier ongoing maintenance - if you have a controller for every table/model it is much harder to change the underlying structure at a later date. Additionally reducing the controllers to main functional area make it more usable - consumers of your system will have a high level view of what is there and should not be concerned with how you decided organize the data.

So, for example, I am writing a travel system and for the holidays part I have maybe a dozen table and model classes so far. I will however have only one controller for holidays since from a system interface perspective this is the only concern of someone interacting with it. A third party should not need to know the underlying structure - they are only concerned with holidays.

To achieve this I have tasks like add_price, display_itinerary, etc on the holidays controller. This means that at any point in the future I can change my table/model structure, update my controller task to reflect this and nothing above that (tasks/views) needs to be changed. I found it very unclear from books and docs that it was possible to do this but Joomla is actually very flexible under the hood. Controllers support multiple models so, for example, my display_itinerary task would look something like:

Code: Select all

	
function display_itinerary()
{
      	$model =& $this->getModel('itinerary');
	$view =& $this->getView( 'holiday', 'html' );
	$view->setModel($model, true);
	$view->display_itinerary('default_itinerary');
}
where I am:

1. Explicitly getting the itinerary model.
2. Creating an instance of the holiday view
3. Explicitly setting the views model to the itinerary one create in step 1.
4. Calling the views display_itinerary function with the default_itinerary template.

Taking this route allows you to structure things a bit looser since the controller, correctly decides what to do.

In terms of the difference between a controller and a model, think of the controller like a manager - it is not there to do any work, just to tell others what to do. So if it needs any data it will ask the model for it and if it needs to show that data to someone it will pass the data to a view telling the view what format (template) it should use.

Hope this helps.
Dave

cheryl100
Joomla! Apprentice
Joomla! Apprentice
Posts: 30
Joined: Tue Mar 17, 2009 2:13 pm

Re: select box from a db table selected option - MVC

Post by cheryl100 » Fri May 15, 2009 8:31 am

Thanks again Dave, your description of the model and controller is very clear, so I only really need one controller file. The models can return stuff to the controllers, the controllers just call the models, they don't return stuff.

$model =& $this->getModel('itinerary');
I know this gets the model itinarary, but what does that mean in terms of files? Can I have more than one class in a file or is it clearer programming to keep classes in seperate files? Does the line
$model =& $this->getModel('itinerary');
mean that I have a file called somename.php in the models folder with a class called itineraryClass.php and some functions within that class? Is the line
$model =& $this->getModel('itinerary');
also a kind of include, meaning all the functions within the class itinary will be available for use when the user does something?
As you can tell I'm not used to making my own classes, I use classes alot in actionscript, write my own functions, and smaller functions that are a bit like your description of controllers so my code is easier to read, but usually just have one big file with all the actionscript in and some xml files with the data and the animation, maybe you could reccomend a good book on creating custom php classes, like my kids, I learn best from example.

Thanks again

cheryl

vividearth
Joomla! Apprentice
Joomla! Apprentice
Posts: 26
Joined: Wed Apr 29, 2009 4:09 pm

Re: select box from a db table selected option - MVC

Post by vividearth » Fri May 15, 2009 3:55 pm

Hi Cheryl

No worries. I am not saying you only need one controller - just that you do not need one per model. Have a look at your models and look at which objects are owned by others. So, for example, if you have an Order and OrderItem model, the OrderItem is owned by the Order - it cannot exist without one - if a model is owned by another one it generally does not need a controller. Just top level models need one. It may be that you only need one but I could not say without knowing what you are building.

Correct, the controllers just create models and pass them to a view for display.
$model =& $this->getModel('itinerary');
I know this gets the model itinarary, but what does that mean in terms of files? Can I have more than one class in a file or is it clearer programming to keep classes in seperate files? Does the line
$model =& $this->getModel('itinerary');
mean that I have a file called somename.php in the models folder with a class called itineraryClass.php and some functions within that class? Is the line
$model =& $this->getModel('itinerary');
also a kind of include, meaning all the functions within the class itinary will be available for use when the user does something?
The call to $this->getModel('itinerary') is a call the getModel function on the JController class. You may need to do some reading on object orientated design here. Basically in your model class you will notice it starts with something like:

Code: Select all

class MyExtentionControllerLocation extends JController
The bit that say "extends JController" means that your model is a type of JController and therefore has all of the functionality that JController has plus anything you add to it - this is why I recommend reading through those core classes - there is a lot of functionality that is included in your classes for free. JController, JModel, JTable and JView are all base classes that yours extend and contain loads of good stuff.

In terms of files the getModel() function, it will call the JModel base classes getInstance function to get a model. In essence what this does is look in your models folder and, in this instance look for a file called itinerary.php. If it finds this file it will include it and then try and create a class of type MyExtentionModelItinerary. It is assuming a naming convention here - your component name followed by Model and finally the model name.

So I would have a models folder with an itinerary.php file and in that file I would have something like this:

Code: Select all

class TravelModelItinerary extends TravelZenModelExtended
{
    // Bug free, ground breaking code here...!
}
A separate file per class is not necessary but I would strongly advise it. Joomla often works on naming conventions to include the correct file so it becomes crucial to stick to one file per class. Also avoid underscores in your class names. For some reason there are places in Joomla that will ignore files with an underscore - I can understand if the file name started with an underscore to indicate it was private but cannot see why it ignores a file like itinerary_item.php. Anyway - just be warned - that one got me the other day.

Again I am not much help with books - I just started PHP and Joomla 3 weeks ago now but have programmed in many languages/frameworks over the last 15+ years so tend to pick up new languages pretty fast without books. php docs online is a great resource for learning php and for Joomla, the docs are ok but I am finding the actual code far more helpful. Read through the core classes - if you see a php function you do not know google it and learn it. Use JDump to dump out variables so you can see what is happening at runtime.

Maybe someone else has some advice on the book front?

A friend has brought this book and says it is pretty good. He also has limited programming experience but is following it ok so it might be about the right level for you.

Dave

cheryl100
Joomla! Apprentice
Joomla! Apprentice
Posts: 30
Joined: Tue Mar 17, 2009 2:13 pm

Re: select box from a db table selected option - MVC

Post by cheryl100 » Wed May 20, 2009 8:15 am

Thanks Dave, l8 reply as haven't had tintenet for a few days... had a look at the book but think it's maybe too easy, I'm an ace at style sheets, so my websites don't look anything like joomla sites, can add comments and am building a component with sub menus, what I'm not sure of is creating custom classes with PHP, or OOP with PHP, I can handle complex string manipulation, write my own functions etc, but am not used to creating seperate files for code, with the book doesn't explain, well, not from the TOC, maybe it does or maybe it assumes that you know all this stuff already, will google an intro to to creating OOP code with PHP, thanks again, is it still OK to email you if I get stuck? Have managed to create 2 language ini files for my component too, but have to find out how to translate the sub menus of the component, I'll ask that one on the language forum though.

cheryl

vividearth
Joomla! Apprentice
Joomla! Apprentice
Posts: 26
Joined: Wed Apr 29, 2009 4:09 pm

Re: select box from a db table selected option - MVC

Post by vividearth » Wed May 20, 2009 8:54 am

Hi Cheryl

Feel free to give me a shout if you get stuck.

Try this for an intro to oophp http://www.killerphp.com/tutorials/object-oriented-php/.

Good luck!
Dave


Locked

Return to “Joomla! 1.5 Coding”