Joomla postSaveHook set jform - php

Im busy with an image moving function so im overriding some controller functions, and unfortuantly i required the items id for the image name so i changed form save() to postSaveHook() as i was not able to get the item id in save() but now im facing another problem i cant set form data to the newly renamed image.
Here's the code:
public function postSaveHook($model, $validData){
$item = $model->getItem();
$id = $item->get('id');
$path = JPath::clean(JPATH_SITE. DS ."images". DS ."menu_slider". DS );
$input=JFactory::getApplication()->input;
$input->get('jform', NULL, NULL);
$src_image = $this->moveOriginal($path,$id);
$imageTest = $this->findImages($src_image);
if(!empty($imageTest)){
foreach($imageTest as $images){
$this->createImageSlices($images,$src_image,$path);
}
}else{
echo 'all images are there';
}
/*this part no longer works*/
$data = JRequest::getVar( 'jform', null, 'post', 'array' );
$data['image'] = 'images'.DS.'menu_slider'.DS.'original'.DS.$src_image;
$input->post->set('jform',$data);
return parent::postSaveHook($model, $validData);
}
is there anyway i can save the data from this? or if i revert back to save, how would i get the id?
Any Help Greatly Appreciated.

I tried different ways and the absolute safest way for me was to add the following code in the model
class DPCasesModelCase extends JModelAdmin {
public function save($data) {
new EventHandler(JDispatcher::getInstance(), $this);
return parent::save($data);
}
}
class EventHandler extends JEvent {
private $model = null;
public function __construct(&$subject, $model) {
parent::__construct($subject);
$this->model = $model;
}
public function onContentChangeState($context, $pks, $value) {
if ($context != 'com_dpcases.case' && $context != 'com_dpcases.form') {
return;
}
if (! is_array($pks)) {
$pks = array($pks);
}
foreach ( $pks as $pk ) {
$this->dowork($this->model->getItem($pk), 'edit');
}
}
public function onContentAfterSave($context, $object, $isNew) {
if ($context != 'com_dpcases.case' && $context != 'com_dpcases.form') {
return;
}
$this->dowork($object, $isNew ? 'create' : 'edit');
}
private function dowork($object, $action) {
...
}
}

Related

ZF2 bind form data

I am trying to bind the form data before I set the edited form data as I don't want to lose values which hasn't be changed. It actually throws me an error and the ZF2 website doesn't provide me a good working example. I am stuck and I don't want to wrote a dirty workaround, someone? :)
I've created a model as follow:
namespace Application\Model;
class Advertisement {
public $id;
public $name;
public $code;
public $banner;
public $fileupload;
public function exchangeArray($data)
{
$this->id = isset($data['id']) ? $data['id'] : null;
$this->name = isset($data['name']) ? $data['name'] : null;
$this->code = isset($data['code']) ? $data['code'] : null;
$this->banner = isset($data['banner']) ? $data['banner'] : '';
$this->fileupload = isset($data['fileupload']) ? $data['fileupload'] : '';
}
public function exchangeJsonToPhpArray($json)
{
}
public function getArrayCopy()
{
return get_object_vars($this);
}
}
My Controller;
public function editAction()
{
# Get Request and Params
$request = $this->getRequest();
$language = $this->params('language');
$id = $this->params('id');
# Get advertisement data
$oAdvertisement = new Advertisement();
if (!$oAdvertisement = $this->getAdvertisementTable()->selectAdvertisementToEdit(array('id' => $id)))
return $this->redirect()->toRoute('admin/advertisement');
# Advertisement form
$sm = $this->getServiceLocator();
$dbAdapter = $sm->get('Zend\Db\Adapter\Adapter');
$form = new AdvertisementForm($dbAdapter, $this->params('language'));
$form->bind($oAdvertisement);
# Post request
$request = $this->getRequest();
if ($request->isPost()) {
# Set post data
$post = array_merge_recursive($this->request->getPost()->toArray(), $this->request->getFiles()->toArray());
$form->setData($post);
# Validate form
if ($form->isValid()) {
# Get form data
$formData = $form->getData();
Debug::dump($form->getData());
# Get service config
$serviceLocator = $this->getServiceLocator();
$config = $serviceLocator->get('config');
$sBannerName = $config['banner_upload_path'] . '/' . md5(mt_rand()) .'.jpg';
# Insert into database
$oAdvertisement->exchangeArray($formData);
# Validate and rename image upload
//.. image upload
Debug::dump($oAdvertisement);
exit;
# Update database record
$this->getAdvertisementTable()->updateAdvertisement($oAdvertisement, $id);
// success..
} else {
// false..
}
}
# Return view model
return new ViewModel(array(
'form' => $form,
));
}
Error;
Fatal error: Cannot use object of type Application\Model\Advertisement as array in ..../module/Application/src/Application/Model/Advertisement.php on line 29
In exchangeArray () method try to test the type of the parameter $ data.
Personally, I put systematically:
if ($data instanceof IteratorAggregate) {
$data = iterator_to_array($data->getIterator(), true);
} elseif ($data instanceof Iterator) {
$data = iterator_to_array($data, true);
} elseif (! is_array($data)) {
throw new Exception(_('Data provided is not an array, nor does it implement Iterator or IteratorAggregate'));
}

PHP - What is wrong? Learning MVC - Beginner

Hy,
i started learning PHP and i created a simple MVC Style Codebase.
The Script just generates a random number and displays this numer. I also write a function to display the number shown before but it does not work. The value is empty. Can you help me out, i have no clue whats wrong and there is no php error thrown.
view.php
<?php
class View
{
private $model;
private $view;
public function __construct()
{
$this->model = new Model();
}
public function output()
{
echo 'Current Entry: ';
echo $this->model->getData();
echo '<br />';
echo 'Update';
echo '<br />';
echo 'Last';
}
public function getModel()
{
return $this->model;
}
}
controller.php
<?php
class Controller
{
private $model;
private $view;
public function __construct($view)
{
$this->view = $view;
$this->model = $this->view->getModel();
}
public function get($request)
{
if (isset($request['action']))
{
if ($request['action'] === 'update')
{
for ($i = 0; $i<6; $i++)
{
$a .= mt_rand(0,9);
}
$this->model->setData($a);
}
elseif ($request['action'] === 'preview')
{
$this->model->setLast();
}
else
{
$this->model->setData('Wrong Action');
}
}
else
{
$this->model->setData('Bad Request');
}
}
}
model.php
<?php
class Model
{
private $data;
private $last;
public function __construct()
{
$this->data = 'Default';
}
public function setData($set)
{
if ( ! (($set == 'Wrong Action') && ($set == 'Bad Request')))
{
$this->last = $this->data;
}
$this->data = $set;
}
public function getData()
{
return $this->data;
}
public function setLast()
{
$this->data = $this->last;
}
public function getLast()
{
return $this->last;
}
}
index.php
<?php
require_once 'controller.php';
require_once 'view.php';
require_once 'model.php';
$view = new View();
$controller = new Controller($view);
if (isset($_GET) && !empty($_GET)) {
$controller->get($_GET);
}
$view->output();
Are there any other, bad mistakes in the Script?
Any input very welcome! :)
The problem with your code is that PHP does not preserve variable values between requests, therefore, when you set your $model->last value here:
$this->last = $this->data;
It gets reset on your next request.
You may want to store $last value in a session or a cookie instead. Something like:
$_SESSION['last'] = $this->data;
And then when you are instantiating your model you could initialize it with a value stored in a session if available:
index.php - add session_start() at the beginning
model.php:
public function __construct()
{
$this->data = isset($_SESSION['last']) ? $_SESSION['last'] : 'Default';
}
public function setData($set)
{
$this->data = $set;
if ( ! (($set == 'Wrong Action') && ($set == 'Bad Request')))
{
$_SESSION['last'] = $this->data;
}
}
controller.php
elseif ($request['action'] === 'preview')
{
//Remove this
//$this->model->setLast();
}

Laravel 5 layout

I was wondering what a general layout in Laravel 5 is like and if it is in L4 so I wrote some code. I've been using teepluss/laravel-theme but I want something of my own. If anyone could give me some ideas it would be useful.
Controller.php:
<?php
abstract class Controller extends BaseController
{
use DispatchesCommands, ValidatesRequests;
protected $layout = null;
function __construct()
{
$this->setLayout();
}
protected function setPageContent($content)
{
if (is_null($this->layout)) {
throw new Exception('layout was not set');
}
return view($this->layout, ['content' => view($content)]);
}
public function setLayout()
{
$lay = DB::table('layout')->where('selected', 1)->first();//i select the layout from a database
return $this->layout = $lay->name . ".layouts." . $lay->name; //create a file with the database name
}
protected function setView($vista)
{
$view = DB::table('layout')->where('selected', 1)->first();
return $view->name . '/' . $vista;
}
}
After that I call getIndex() in MainController.php:
public function getIndex($page = null)
{
if ($page == null) {
return $this->setPageContent($this->setView('index'));
} else {
return $this->setPageContent($this->setView($page));
}
}
routes.php:
Route::controller('/{page?}/{param?}', 'MainController');

Joomla Comonent update data

I'm working on a Joomla 3 component. Currently I'm programming the backend. I'm having a form to add new data and it is working quite well. But when I want to update the data the component creates a new item instead of updating the existing.
I was searching for position which let Joomla know, that this is an update, but without success.
So my question: what is the information that makes Joomla updating the data?
My Code:
Table:ia.php
class mkTableia extends JTable
{
/**
* Constructor
*
* #param object Database connector object
*/
function __construct(&$db)
{
parent::__construct('#__tbl_ia', 'ID', $db);
}
}
Model: ia.php
class mkModelia extends JModelAdmin
{
public function getTable($type = 'ia', $prefix = 'mkTable', $config = array())
{
return JTable::getInstance($type, $prefix, $config);
}
public function getForm($data = array(), $loadData = true)
{
// Get the form.
$form = $this->loadForm('com_mk.ia', 'ia',
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_mk.edit.ia.data', array());
if (empty($data))
{
$data = $this->getItem();
}
return $data;
}
}
View:view.html.php
class mkViewia extends JViewLegacy
{
/**
* display method of Hello view
* #return void
*/
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);
}
/**
* Setting the toolbar
*/
protected function addToolBar()
{
$input = JFactory::getApplication()->input;
$input->set('hidemainmenu', true);
$isNew = ($this->item->ID == 0);
JToolBarHelper::title($isNew ? JText::_('COM_MK_MANAGER_MK_NEW')
: JText::_('COM_MK_MANAGER_MK_EDIT'));
JToolBarHelper::save('IA.save');
JToolBarHelper::cancel('IA.cancel', $isNew ? 'JTOOLBAR_CANCEL'
: 'JTOOLBAR_CLOSE');
}
}

php csrf protection library

Are there any libraries to protect against CSRF(PHP5.1/5.2) or do I need to create on myself? I use this snippet from Chris, but without a library I am getting a lot of duplication on every page.
I found this library for PHP5.3, but I am wondering if there are any on PHP5.1/5.2 because I don't believe yet all hosting support PHP5.3.
Since I use Kohana - I've just extended couple of its core classes. It can be used in any code with a little changes though:
class Form extends Kohana_Form
{
public static function open($action = NULL, array $attributes = null)
{
if (is_null($action))
{
$action = Request::current()->uri . ($_SERVER['QUERY_STRING'] ? '?' . $_SERVER['QUERY_STRING'] : '');
}
$open = parent::open($action, $attributes);
$open .= parent::hidden(self::csrf_token_field(), self::csrf_token());
return $open;
}
public static function csrf_token_field()
{
return 'csrf_token';
}
public static function csrf_token()
{
$session = Session::instance();
$token = $session->get(self::csrf_token_field());
if (!$token)
{
$session->set(self::csrf_token_field(), $token = md5(uniqid()));
}
return $token;
}
}
class Validate extends Kohana_Validate
{
public function __construct(array $array, $csrf = true)
{
parent::__construct($array);
if ($csrf)
$this->add_csrf();
}
public static function factory(array $array, $csrf = true)
{
return new Validate($array, $csrf);
}
private function add_csrf()
{
$this->rules(form::csrf_token_field(), array(
'not_empty' => array(),
'csrf' => array()
));
}
protected function csrf($token)
{
return $token == form::csrf_token();
}
}

Categories