Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get an array the correct way in Joomla (2.5/3.x)

<form>
<input type="checkbox" name="item[]" value="1" />
<input type="checkbox" name="item[]" value="2" />
<input type="checkbox" name="item[]" value="3" />
</form>
<?php
$app = JFactory::getApplication();
$items = $_POST['type']; // This works but is not Joomla wise...

$items = $app->input->getArray(array('type_ids')); // Tried multiple ways but can't get it to work.
?>

What should be the correct way to load all form items into an array $items?

like image 596
COBIZ webdevelopment Avatar asked May 03 '13 10:05

COBIZ webdevelopment


2 Answers

If you just want all the items, the Joomla way would be:

$items = JRequest::getVar('item', array());

where the second parameter would be your default value if 'item' is not set. But note that this fetches the params via the name, just as usual.

The same using the Joomla Platform 11.1 and above would be:

$items = $app->input->get('item', array(), 'ARRAY');

Here the third parameter is necessary since the default filter is 'cmd' which does not allow arrays. More information in the docs.

like image 177
Mallard Avatar answered Sep 28 '22 19:09

Mallard


If you are using JForm to make forms, you need to extract the posted data from the jform array.

For the native 3.x components the code will look inside the controller like:

    // Get POSTed data
    $data  = $this->input->post->get('jform', array(), 'array');

where $this->input is the input object, inherited from JControllerBase.

For the components using legacy MVC classes, the code will be:

    // Get input object
    $jinput = JFactory::getApplication()->input;

    // Get posted data
    $data  = $jinput->post->get('jform', array(), 'array');

Security notice:

ARRAY - Attempts to convert the input to an array. Like

$result = (array) $source;

The data array itself is NOT sanitized.

like image 42
Valentin Despa Avatar answered Sep 28 '22 19:09

Valentin Despa