Zend-Image Uploading at Wrong Destination - zend-framework

please help..I'm newbies and try to learn Zend Framework, but have problem when uploading image.
The script at file Application.ini
uploads.uploadPath = APPLICATION_PATH "/../public/uploads"
Form to upload Image:
$this->setAction('/data/personil/create')
->setMethod('post');
//Item input untuk gambar
$images = new Zend_Form_Element_File('images');
$images->setMultiFile(3)
->addValidator('IsImage')
->addValidator('Size', false, '204800')
->addValidator('Extension', false, 'jpg,png,gif')
->addValidator('ImageSize', false, array(
'minwidth' => 150,
'minheight' => 150,
'maxwidth' => 700,
'maxheight' => 700
))
->setValueDisabled(true);
// attach element to form
$this->addElement($images);
// create display group for file elements
$this->addDisplayGroup(array('images'), 'files');
$this->getDisplayGroup('files')
->setOrder(40)
->setLegend('Images');
Controller action create :
public function createAction()
{
$form = new Pengadilan_Form_PersonilCreate();
$this->view->form = $form;
$flashMessenger = $this->_helper->FlashMessenger;
//SImpan kedatabase
if($this->getRequest()->isPost()){
if($form->isValid($this->getRequest()->getPost())){
$personil = new Pengadilan_Model_Personil();
$personil->fromArray($form->getValues());
$personil->RecordDate = date('Y-m-d', mktime());
$personil->DisplayStatus = 0;
$personil->DisplayUntil = null;
$personil->save();
$id = $personil->RecordId;
$config = $this->getInvokeArg('bootstrap')->getOption('uploads');
$form->images->setDestination($config['uploadPath']);
$adapter = $form->images->getTransferAdapter();
for($x=0; $x<$form->images->getMultiFile(); $x++) {
$xt = #pathinfo($adapter->getFileName('images_'.$x.'_'), PATHINFO_EXTENSION);
$adapter->clearFilters();
$adapter->addFilter('Rename', array(
'target' => sprintf('%d_%d.%s', $id, ($x+1), $xt),
'overwrite' => true
));
$adapter->receive('images_'.$x.'_');
}
$this->_helper->getHelper('FlashMessenger')->addMessage('Data sekses diinput ke database #' . $id . '. Admin akan segera merivew, jika diterima, akan ditampilkan dalam waktu 48 jam, Terima kasih.');
$this->_redirect('/data/personil/sukses');
}
}
}
Controller action display :
public function displayAction()
{
//Pertama setting filters
$filters = array(
'id' => array('HtmlEntities', 'StripTags', 'StringTrim')
);
$validators = array(
'id' => array('NotEmpty', 'Int')
);
$input = new Zend_Filter_Input($filters, $validators);
$input->setData($this->getRequest()->getParams());
if($input->isValid()){
$q = Doctrine_Query::create()
->from('Pengadilan_Model_Personil p')
->leftJoin('p.Pengadilan_Model_Jabatan j')
->leftJoin('p.Pengadilan_Model_Tupoksi t')
->leftJoin('p.Pengadilan_Model_Golongan g')
->leftJoin('p.Pengadilan_Model_Agama a')
->leftJoin('p.Pengadilan_Model_Kelamin k')
->where('p.RecordId = ?', $input->id)
->addWhere('p.DisplayStatus = 1')
->addWhere('p.DisplayUntil >= CURDATE()');
$result = $q->fetchArray();
if(count($result) == 1){
$this->view->personil = $result[0];
$this->view->images = array();
$config = $this->getInvokeArg('bootstrap')->getOption('uploads');
foreach (glob("{$config['uploadPath']}/{$this->view->item['RecordID']}_*") as $file) {
$this->view->images[] = basename($file);
}
}else{
throw new Zend_Exception('Maaf, halaman tidak ditemukan, 404');
}
}else{
throw new Zend_Exception('Kesalahan Input');
}
}
The last script at view : display.phtml
<div id="images">
<?php foreach ($this->images as $image): ?>
<img src="/uploads/<?php echo $this->escape($image); ?>" width="150" height="150" />
<?php endforeach; ?>
Image upload Destination at config is /public/uploads
in my case image at /public
Image succes to upload and renamed but outside the directory and
Image won't displayed at display.phtml
Many thanks for your help..

First you need to set your form encoding File element link$form->setAttrib('enctype', 'multipart/form-data');
Also you should probably finish setting up your image element before you POST the form not after. So move the setDestination stuff up to where you initialize the form, you may have a better chance of it working.
public function createAction()
{
$form = new Pengadilan_Form_PersonilCreate();
//set form encoding
$form->setAttrib('enctype', 'multipart/form-data');
//get path and set destination for image element
$config = $this->getInvokeArg('bootstrap')->getOption('uploads');
$form->images->setDestination($config['uploadPath']);
$this->view->form = $form;
//consider intializing flash messenger in the init() method
$flashMessenger = $this->_helper->FlashMessenger;
//SImpan kedatabase
if($this->getRequest()->isPost()){
if($form->isValid($this->getRequest()->getPost())){
//more code...
$adapter = $form->images->getTransferAdapter();
for($x=0; $x<$form->images->getMultiFile(); $x++) {
$xt = #pathinfo($adapter->getFileName('images_'.$x.'_'), PATHINFO_EXTENSION);
$adapter->clearFilters();
$adapter->addFilter('Rename', array(
'target' => sprintf('%d_%d.%s', $id, ($x+1), $xt),
'overwrite' => true
));
$adapter->receive('images_'.$x.'_');
}
$this->_helper->getHelper('FlashMessenger')->addMessage('Data sekses diinput ke database #' . $id . '. Admin akan segera merivew, jika diterima, akan ditampilkan dalam waktu 48 jam, Terima kasih.');
$this->_redirect('/data/personil/sukses');
}
}
}
not sure if this will fix everything but it should be a start...

Related

bootstrap mail form $from<$email> $fromEmail

I refer to this page. https://bootstrapious.com/p/how-to-build-a-working-bootstrap-contact-form and i uesd index-2.html / contact-2.php files.
i want mailheader ''
but code is
**$fromEmail = 'demo#domain.com';
$fromName = 'Demo contact form';**
$sendToEmail = 'my#mail.com';
$fields = array('name' => 'Name', 'phone' => 'Phone', 'email' => 'Email', "\r\n" , 'message' => 'Message');
so i changed
$fromEmail = "$email" $fromName = '$name'; or
$fromEmail = $_POST['form_email']; $name = $_POST['name'];
but It just makes an error.
ex) Root User" '
try
{
if(count($_POST) == 0) throw new \Exception('Form is empty');
$emailTextHtml .= "<table>";
foreach ($_POST as $key => $value) {
// If the field exists in the $fields array, include it in the email
if (isset($fields[$key])) {
$emailTextHtml .= "<tr><th>$fields[$key]</th><td>$value</td></tr>";
}
}
$emailTextHtml .= "</table>";
$mail = new PHPMailer;
$mail->setFrom($fromEmail, $fromName);
$mail->addAddress($sendToEmail, $sendToName); // you can add more addresses by simply adding another line with $mail->addAddress();
$mail->addReplyTo($from);
$mail->isHTML(true);
$mail->Subject = $subject;
$mail->msgHTML($emailTextHtml); //
what should I do?
$fromEmail = 'demo#domain.com';
$fromName = 'Demo contact form'
How should I change it?

Yii2-advanced : dataProvider

I want to increment my dataProvider in siteController. That is, at each iteration, my dataProvider should be incremented by 1 & renamed as dataProvider1,dataProvider2,dataProvider3,....& so on.
I tried to append $i to dataProvider, but it says 'dataProvider can't be converted to String...!'
My actionIndex is as follows :
public function actionIndex()
{
$query = new \yii\db\Query;
for ($i = 1; $i <= 20; $i++) {
$query->select('*')->from('business_main_categories')->where(['bmc_id' => $i]);
$query->createCommand();
$dataProvider.$i = new ActiveDataProvider([
'query' => $query,
'pagination' => false,
]);
return $this->render('index', [
'dataProvider' => $dataProvider.$i,
]);
}
}
And, I also want to user that dataProvider in my 'index.php' with iterations; I tried to insert a for loop & written all statements in 'echo', but I'm unable to get it done.
My way to access it in 'index.php' is as follows :
<?= GridView::widget([
'dataProvider' => $dataProvider,
'summary' => '',
'columns' => [
[
'attribute' => 'bmc_image',
'format' => 'html',
'label' => '',
'value' => function ($data) {
return Html::img($data['bmc_image'],
['width' => '190px']);
},
],
]
]); ?>
Please help me to solve my issue.
I solved my problem without using gridview. As follows -
My SiteController -
public function actionIndex()
{
$searchModel = new BusinessMainCategoriesSearch();
$dataProvider = $searchModel->search(Yii::$app->request->queryParams);
$dataProvider->pagination->pageSize = $dataProvider->getTotalCount(); //-1 : disable
return $this->render('index', [
'searchModel' => $searchModel,
'dataProvider' => $dataProvider,
]);
}
using this code I get all records in dataProvider from my db.
(Note that, I'm using ActiveDataProvider in my 'BusinessMainCategoriesSearch' model)
And, my index.php is -
<?php
$m = $dataProvider->getModels();
foreach ($m as $dp) {
echo "<img src = '".$dp['bmc_image']."' />";
echo '<center><font color = "white">'.$dp['bmc_name'].'<font/></center>';
} ?>
It worked great for me & it's a easiest way to do so.

How to insert and retrive records into Database in moodle

Hai i want to insert my form fields into database and retrive records from database in moodle. how to do that :
Here is my form what i created :
Uplo.php
<?php
require_once('config.php');
require_once("$CFG->libdir/formslib.php");
class uplo extends moodleform {
public function definition() {
global $CFG;
$mform = $this->_form;
$buttonarray=array();
$mform->addElement('text', 'name', get_string('name'));
$mform->setType('name', PARAM_NOTAGS);
$mform->setDefault('name', 'Please enter name');
$mform->addElement('text', 'email', get_string('email'));
$mform->setType('email', PARAM_NOTAGS);
$mform->setDefault('email', 'Please enter email');
$buttonarray[] = &$mform->createElement('submit', 'submitbutton', get_string('savechanges'));
$buttonarray[] = &$mform->createElement('cancel');
$mform->addGroup($buttonarray, 'buttonar', '', array(' '), false);
$mform->closeHeaderBefore('buttonar');
}
function validation($data, $files) {
return array();
}
}
?>
Testing.php:
<?php
define('_DB_HOST_NAME','localhost');
define('_DB_USER_NAME','root');
define('_DB_PASSWORD','');
define('_DB_DATABASE_NAME','moodle_test');
$dbConnection = mysqli_connect(_DB_HOST_NAME,_DB_USER_NAME,_DB_PASSWORD,_DB_DATABASE_NAME);
?>
<?php
require_once('uplo.php');
$mform = new uplo();
$mform->display();
if(isset($_POST['submitbutton'])){
$name = $mform->get_data('name');
$email = $mform->get_data('email');
$table='insert';
$res=insert_record($table, $name,$email, $returnid=true, $primarykey='id') ;
}
?>
This one is i tried. how to do that in a right way
Make sure you require_once(dirname(FILE).'/../../config.php') (adjust the number of '/../' based on the subdirectory your file is in, relative to config.php).
The use the Moodle data manipulation API https://docs.moodle.org/dev/Data_manipulation_API

Auditlogging functionality for zend db

I have a requirement to implement audit logging functionality in a zend project. The models are created using zend db and the update function is as follows.
public function updateGroup($data,$id)
{
$row = $this->find($id)->current();
// set the row data
$row->name = $data['name'];
$row->description = $data['description'];
$row->updatedBy = $data['updatedBy'];
$row->updatedOn = date('Y-m-d H:i:s');
$id = $row->save();
return $id;
}
I have to create a table with the auditlog information which includes the current userid. I have tried many methods and nothing is a good solution. What is the best practice for a good audit logging functionality for zend?
I just want to log only the modified data. and the log table schema is like
id,
table,
column,
rowId
oldvalue,
newvalue,
updatedon,
updatedbyuser
use Zend_Log_Writer_Db :
Zend_Log_Writer_Db writes log information to a database table using
Zend_Db. The constructor of Zend_Log_Writer_Db receives a
Zend_Db_Adapter instance, a table name, and a mapping of database
columns to event data items
for example :
$columnMapping = array('name' => 'name',
'desc' => 'desc',
'updatedBy' => 'userid',
'updatedOn' => 'date');
$writer = new Zend_Log_Writer_Db($db, 'auditlog_table', $columnMapping);
$logger = new Zend_Log($writer);
$logger->setEventItem('name', $data['name']);
$logger->setEventItem('desc', $data['name']);
$logger->setEventItem('updatedBy',$data['updatedBy']);
$logger->setEventItem('updatedOn',date('Y-m-d H:i:s'));
EDIT : to log only the modified data :
public function logUpdate(array $values)
{
$columnMapping = array('id' => 'id',
'table' => 'table',
'column' => 'column',
'rowId' => 'rowId',
'oldvalue' => 'oldvalue',
'newvalue' => 'newvalue',
'updatedon' => 'updatedon',
'updatedbyuser' => 'updatedbyuser');
$writer = new Zend_Log_Writer_Db($db, 'auditlog_table', $columnMapping);
$logger = new Zend_Log($writer);
$logger->setEventItem('id', $values['id']);
$logger->setEventItem('table', $values['table']);
$logger->setEventItem('column', $values['column']);
$logger->setEventItem('rowId', $values['rowId']);
$logger->setEventItem('oldvalue', $values['oldValue']);
$logger->setEventItem('newValue', $values['newValue']);
$logger->setEventItem('updatedon', $values['updatedon']);
$logger->setEventItem('updatedbyuser', $values['updatedbyuser']);
}
and in updateGroup :
public function updateGroup($data,$id)
{
$row = $this->find($id)->current();
$values = array('table' => $this->name);
$values = array('updatedon' => $data['updatedBy']);
$values = array('updatedbyuser' => date('Y-m-d H:i:s'));
//go through all data to log the modified columns
foreach($data as $key => $value){
//check if modified log the modification
if($row->$key != $value){
$values = array('column' => $key);
$values = array('oldValue' => $row->$key);
$values = array('newValue' => $value);
logUpdate($values);
}
}
// set the row data
$row->name = $data['name'];
$row->description = $data['description'];
$row->updatedBy = $data['updatedBy'];
$row->updatedOn = date('Y-m-d H:i:s');
$id = $row->save();
return $id;
}
Note that its better to implement logging for all your application and seperate logging from update , see this answer for that .

Multistep drupal form with tables

Can anyone tell me how to make a multi-step drupal form which prints a table in one of the steps?-
This is the code I already have, it corresponds to the second step of the form. It throws me this error:
Fatal error: Cannot unset string offsets in C:\wamp\www\academicus\includes\form.inc on line 497
function listarAlumnos($nombre, $apellido) {
if($nombre=='') {
$consulta="SELECT * FROM Pinteres WHERE PinApe1='".$apellido."' or PinApe2='".$apellido;
} else if ($apellido=='') {
$consulta="SELECT * FROM Pinteres WHERE PinNom1='".$nombre."' or PinNom2='".$nombre."'";
} else {
$consulta="SELECT * FROM Pinteres WHERE (PinNom1='".$nombre."' or PinNom2='".$nombre."') AND (PinApe1='".$apellido."' or PinApe2='".$apellido."')";
}
$resultado=consultarContacta($consulta);
$form=array();
$header = array(t('Id'), t('Primer nombre'), t('Segundo nombre'), t('Primer apellido'), t('Segundo apellido'), t('Direccion'), t('Telefono'), t('Celular'), t('Email'));
$rows = array();
while ($rs=odbc_fetch_array($resultado)) {
$row=array();
$id=$rs['PinId'];
$primerNombre=$rs['PinNom1'];
$segundoNombre=$rs['PinNom2'];
$primerApellido=$rs['PinApe1'];
$segundoApellido=$rs['PinApe2'];
$direccion=$rs['PinDir'];
$telefono=$rs['PinTelPri'];
$celular=$rs['PinTelCel'];
$email=$rs['PinEMail'];
$row[] = $id;
$row[] = $primerNombre;
$row[] = $segundoNombre;
$row[] = $primerApellido;
$row[] = $segundoApellido;
$row[] = $direccion;
$row[] = $telefono;
$row[] = $celular;
$row[] = $email;
$rows[] = $row;
};
$form['IdIngresado'] = array (
'#title' => t('Id interesado a importar'),
'#type' => 'textfield',
'#required' => TRUE,
'#description' => t('Ingrese el id del interesado a importar de los listados arriba.')
);
$form['CedulaIngresada'] = array (
'#title' => t('Cedula interesado a importar'),
'#type' => 'textfield',
'#required' => TRUE,
'#description' => t('Ingrese la cedula del interesado a importar.')
);
$form['finalizar'] = array (
'#type' => 'submit',
'#value' => t('Finalizar')
);
$output .= theme('table', $header, $rows);
$output .= drupal_render($form);
return $output;
}
I could make it work using some code like this:
$form['serial'] = array(
'#type' => 'textfield',
'#title' => t('serial number'),
'#prefix' => '<table><tr><td>',
'#suffix' => '</td>',
);
but I know it's not the proper way of doing it.
I assume you know how to do the multi-step form. For the table, you can use Drupal's table theme function. If the table contains only markup, you can do something like this:
$form['table'] = array ('#value' => theme('table', $headers, $rows));
$headers are the table headers and $rows are your data.
If the table contains actual form elements (such as selects, textfields, etc.), you can wrap them in a form element that calls a theme function, like so:
$form['table'] = array ('#theme' => 'output_table');
$form['table']['element_1'] = array (...);
$form['table']['element_2'] = array (...);
Within 'theme_output_table', generate your $headers and $rows to feed to 'theme_table' by calling 'drupal_render' on the relevant form elements that are children of $form['table'].