Undefined index: sub - php
I have problem with upload field. Error page image
Actualy when I add upload field to form script gives an error.
The server gives an error for this line: $filenamefields[$group]['sub']
foreach ($fields as $group => $fieldlist) {
if (isset($fieldlist['active']) && $fieldlist['active']) {
$min_req = true;
if (isset($fieldlist['sub'])) {
$this->customrule_addrec(
$fieldlist['sub'],
$required, $title,
$type,
$gprefix.'[' . $group . '][sub]',
$filenamefields[$group]['sub'],
$filetypefields[$group]['sub'],
$filetmpnamefields[$group]['sub'],
$fileerrorfields[$group]['sub'],
$filesizefields[$group]['sub']);
and this line: $this->files['size']['fields']);
$min_req = $this->customrule_addrec($fields, $required, $title, $type, '',
$this->files['name']['fields'],
$this->files['type']['fields'],
$this->files['tmp_name']['fields'],
$this->files['error']['fields'],
$this->files['size']['fields']);
if (!$min_req)
$this->addError($attribute, 'Select a group');
file codes :
<?php
class Orders extends CActiveRecord
{
public $fields;
public $files;
public $file;
public $remove;
public function tableName()
{
return 'orders';
}
public function rules()
{
return array(
array(
'name, start_date, ordertype, user',
'required'
),
array(
'status, ordertype, user',
'numerical',
'integerOnly' => true
),
array(
'name',
'length',
'max' => 200
),
array(
'finish_date, desc',
'safe'
),
array(
'id, name, start_date, finish_date, status, ordertype, user, desc',
'safe',
'on' => 'search'
),
array(
'fields,files',
'safe'
),
array(
'fields',
'customrule_add',
'on' => 'add'
),
array(
'fields',
'customrule_edit',
'on' => 'edit'
),
array(
'file, remove',
'safe',
'on' => 'answer'
)
);
}
public function customrule_add($attribute, $params)
{
$fieldtypes = Orderfield::model()->findAll('ordergroup in (select id from ' . Ordergroup::model()->tableName() . ' where orderform = \'' . $this->ordertype . '\')');
$required = CHtml::listData($fieldtypes, 'id', 'required');
$title = CHtml::listData($fieldtypes, 'id', 'name');
$type = CHtml::listData($fieldtypes, 'id', 'type');
$fields = $this->$attribute;
$min_req = $this->customrule_addrec($fields, $required, $title, $type, '',
$this->files['name']['fields'],
$this->files['type']['fields'],
$this->files['tmp_name']['fields'],
$this->files['error']['fields'],
$this->files['size']['fields']);
if (!$min_req)
$this->addError($attribute, 'Select a group');
}
private function customrule_addrec($fields, $required, $title, $type, $gprefix, $filenamefields, $filetypefields, $filetmpnamefields, $fileerrorfields, $filesizefields)
{
$min_req = false;
foreach ($fields as $group => $fieldlist) {
if (isset($fieldlist['active']) && $fieldlist['active']) {
$min_req = true;
if (isset($fieldlist['sub'])) {
$this->customrule_addrec(
$fieldlist['sub'],
$required, $title,
$type,
$gprefix.'[' . $group . '][sub]',
$filenamefields[$group]['sub'],
$filetypefields[$group]['sub'],
$filetmpnamefields[$group]['sub'],
$fileerrorfields[$group]['sub'],
$filesizefields[$group]['sub']);
foreach ($fieldlist['sub'] as $sgroup => $sfieldlist) {
if (isset($sfieldlist['active']) && $sfieldlist['active']) {
foreach ($sfieldlist as $key => $value) {
if (($key != 'active') && ($key != 'sub') && $required[$key]) {
if ($type[$key] != 2) {
if (!$value)
$this->addError('fields[' . $group . '][sub][' . $sgroup . '][' . $key . ']', 'Value ' . $title[$key] . ' Can not be empty');
} else if (!isset($this->files['name']['fields'][$group]['sub'][$sgroup][$key]) || !$this->files['name']['fields'][$group]['sub'][$sgroup][$key]) {
$this->addError('fields[' . $group . '][sub][' . $sgroup . '][' . $key . ']', 'File ' . $title[$key] . ' Must send');
}
}
}
}
}
}
foreach ($fieldlist as $key => $value) {
if (($key != 'active') && ($key != 'sub') && $required[$key]) {
if ($type[$key] != 2) {
if (!$value)
$this->addError('fields' . $gprefix . '[' . $group . '][' . $key . ']', 'Value ' . $title[$key] . ' Can not be empty');
} else if (!isset($filenamefields[$group][$key]) || !$filenamefields[$group][$key]) {
$this->addError('fields' . $gprefix . '[' . $group . '][' . $key . ']', 'File ' . $title[$key] . ' Must send');
}
}
}
}
}
return $min_req;
}
public function customrule_edit($attribute, $params)
{
$fieldtypes = Orderfield::model()->findAll('ordergroup in (select id from ' . Ordergroup::model()->tableName() . ' where orderform = \'' . $this->ordertype . '\')');
$required = CHtml::listData($fieldtypes, 'id', 'required');
$title = CHtml::listData($fieldtypes, 'id', 'name');
$type = CHtml::listData($fieldtypes, 'id', 'type');
$groups = CHtml::listData(Ordergroup::model()->findAll(array(
'select' => 'id,name,orderform',
'condition' => 'orderform = \'' . $this->ordertype . '\''
)), 'id', 'name');
$fields = $this->$attribute;
$min_req = false;
foreach ($fields as $group => $fieldlist) {
if (isset($fieldlist['active']) && $fieldlist['active']) {
$min_req = true;
if (isset($fieldlist['sub'])) {
foreach ($fieldlist['sub'] as $sgroup => $sfieldlist) {
if (isset($sfieldlist['active']) && $sfieldlist['active']) {
foreach ($sfieldlist as $key => $value) {
if (($key != 'active') && ($key != 'sub') && $required[$key]) {
if ($type[$key] != 2) {
if (!$value)
$this->addError('fields[' . $group . '][sub][' . $sgroup . '][' . $key . ']', 'value ' . $title[$key] . ' Can not be empty');
}
}
}
}
}
}
foreach ($fieldlist as $key => $value) {
if (($key != 'active') && $required[$key]) {
if ($type[$key] != 2) {
if (!$value)
$this->addError('fields[' . $group . '][' . $key . ']', 'value ' . $title[$key] . 'Can not be empty');
}
}
}
}
}
if (!$min_req)
$this->addError($attribute, 'Choose a group');
}
public function add()
{
$name = $this->name;
$exists = Orders::model()->exists('`name` = \'' . $name . '\'');
if ($exists) {
$count = Orders::model()->count('`name` regexp \'^' . $name . ' - [0-9]+$\'');
$this->name = $name . ' - ' . ($count + 2);
}
$status = $this->save();
$status = $this->addsub(
$this->fields,
$status,
$this->files['name']['fields'],
$this->files['type']['fields'],
$this->files['tmp_name']['fields'],
$this->files['error']['fields'],
$this->files['size']['fields']
);
if (!$status) {
Ordervalues::model()->deleteAllByAttributes(array(
'order' => $this->id
));
GroupOfOrder::model()->deleteAllByAttributes(array(
'order' => $this->id
));
$this->delete();
return false;
}
return true;
}
private function addsub($thisfields, $status, $filenamefields, $filetypefields, $filetmpnamefields, $fileerrorfields, $filesizefields)
{
foreach ($thisfields as $group => $fieldlist) {
if (isset($fieldlist['active']) && $fieldlist['active'] && $status) {
$gofo = new GroupOfOrder('insert');
$gofo->group = $group;
$gofo->order = $this->id;
$gofo->save();
if (isset($fieldlist['sub'])) {
$status = $this->addsub(
$fieldlist['sub'],
$status,
$filenamefields[$group]['sub'],
$filetypefields[$group]['sub'],
$filetmpnamefields[$group]['sub'],
$fileerrorfields[$group]['sub'],
$filesizefields[$group]['sub']
);
if(!$status)
return false;
}
foreach ($fieldlist as $key => $value) {
if ($key != 'active' && $key != 'sub' && $status) {
$ftype = Orderfield::model()->findByPk($key);
if (!$ftype) {
$this->addError('fields', 'Field type error');
Ordervalues::model()->deleteAllByAttributes(array(
'order' => $this->id
));
GroupOfOrder::model()->deleteAllByAttributes(array(
'order' => $this->id
));
$this->delete();
return false;
}
if (!empty($value)) {
$field = new Ordervalues('insert');
$field->field = $key;
$field->order = $this->id;
$field->value = $value;
$status = ($status && $field->save());
} elseif (isset($filenamefields[$group][$key]) && !empty($filenamefields[$group][$key])) {
$file = new CUploadedFile($filenamefields[$group][$key], $filetmpnamefields[$group][$key], $filetypefields[$group][$key], $filesizefields[$group][$key], $fileerrorfields[$group][$key]);
if ($ftype->file_type) {
$all = explode("|", $ftype->file_type); // check every allowed extensions with uploaded file
$allowed = false;
foreach ($all as $ex) {
if ($ex == $file->extensionName) {
$allowed = true;
break;
}
}
if (!$allowed) {
$this->addError('files', 'This format' . $file->extensionName . 'is not true');
Ordervalues::model()->deleteAllByAttributes(array(
'order' => $this->id
));
GroupOfOrder::model()->deleteAllByAttributes(array(
'order' => $this->id
));
$this->delete();
return false;
}
}
$ffield = new Ordervalues('insert');
$ffield->field = $key;
$ffield->order = $this->id;
$ffield->value = $file->name;
$ffield->file_size = $file->size;
$status = ($status && $ffield->save());
$status = ($status && $file->saveAs('files/' . $ffield->id));
}
}
}
}
}
return true;
}
public function edit()
{
$status = true;
foreach ($this->fields as $group => $fieldlist) {
if (isset($fieldlist['active']) && $fieldlist['active']) {
$gofo = GroupOfOrder::model()->findByAttributes(array(
'order' => $this->id,
'group' => $group
));
if (!$gofo) {
$gofo = new GroupOfOrder('insert');
$gofo->group = $group;
$gofo->order = $this->id;
$gofo->save();
}
if (isset($fieldlist['sub'])) {
foreach ($fieldlist['sub'] as $sgroup => $sfieldlist) {
if (isset($sfieldlist['active']) && $sfieldlist['active']) {
$sgofo = GroupOfOrder::model()->findByAttributes(array(
'order' => $this->id,
'group' => $sgroup
));
if (!$sgofo) {
$sgofo = new GroupOfOrder('insert');
$sgofo->group = $sgroup;
$sgofo->order = $this->id;
$sgofo->save();
}
foreach ($sfieldlist as $key => $value) {
if ($key != 'active' && $key != 'sub' && $status) {
$ftype = Orderfield::model()->findByPk($key);
if (!$ftype) {
$this->addError('fields', 'Field type error');
return false;
}
if (!empty($value)) {
$field = Ordervalues::model()->findByAttributes(array(
'order' => $this->id,
'field' => $key
));
if (!$field) {
$field = new Ordervalues('insert');
$field->field = $key;
$field->order = $this->id;
}
$field->value = $value;
$status = ($status && $field->save());
} elseif (isset($this->files['name']['fields'][$group]['sub'][$sgroup][$key]) && !empty($this->files['name']['fields'][$group]['sub'][$sgroup][$key])) {
$file = new CUploadedFile($this->files['name']['fields'][$group]['sub'][$sgroup][$key], $this->files['tmp_name']['fields'][$group]['sub'][$sgroup][$key], $this->files['type']['fields'][$group]['sub'][$sgroup][$key], $this->files['size']['fields'][$group]['sub'][$sgroup][$key], $this->files['error']['fields'][$group]['sub'][$sgroup][$key]);
if ($ftype->file_type) {
$all = explode("|", $ftype->file_type); // check every allowed extensions with uploaded file
$allowed = false;
foreach ($all as $ex) {
if ($ex == $file->extensionName) {
$allowed = true;
break;
}
}
if (!$allowed) {
$this->addError('files', 'This format ' . $file->extensionName . ' is not true');
return false;
}
}
$ffield = Ordervalues::model()->findByAttributes(array(
'order' => $this->id,
'field' => $key
));
if (!$ffield) {
$ffield = new Ordervalues('insert');
$ffield->field = $key;
$ffield->order = $this->id;
}
$ffield->value = $file->name;
$ffield->file_size = $file->size;
$status = ($status && $ffield->save());
$status = ($status && $file->saveAs('files/' . $ffield->id));
}
}
}
}
}
}
foreach ($fieldlist as $key => $value) {
if ($key != 'active' && $key != 'sub' && $status) {
$ftype = Orderfield::model()->findByPk($key);
if (!$ftype) {
$this->addError('fields', 'Field error');
return false;
}
if (!empty($value)) {
$field = Ordervalues::model()->findByAttributes(array(
'order' => $this->id,
'field' => $key
));
if (!$field) {
$field = new Ordervalues('insert');
$field->field = $key;
$field->order = $this->id;
}
$field->value = $value;
$status = ($status && $field->save());
} elseif (isset($this->files['name']['fields'][$group][$key]) && !empty($this->files['name']['fields'][$group][$key])) {
$file = new CUploadedFile($this->files['name']['fields'][$group][$key], $this->files['tmp_name']['fields'][$group][$key], $this->files['type']['fields'][$group][$key], $this->files['size']['fields'][$group][$key], $this->files['error']['fields'][$group][$key]);
if ($ftype->file_type) {
$all = explode("|", $ftype->file_type); // check every allowed extensions with uploaded file
$allowed = false;
foreach ($all as $ex) {
if ($ex == $file->extensionName) {
$allowed = true;
break;
}
}
if (!$allowed) {
$this->addError('files', 'This format ' . $file->extensionName . ' is not true');
return false;
}
}
$ffield = Ordervalues::model()->findByAttributes(array(
'order' => $this->id,
'field' => $key
));
if (!$ffield) {
$ffield = new Ordervalues('insert');
$ffield->field = $key;
$ffield->order = $this->id;
}
$ffield->value = $file->name;
$ffield->file_size = $file->size;
$status = ($status && $ffield->save());
$status = ($status && $file->saveAs('files/' . $ffield->id));
}
}
}
} else {
$gofo = GroupOfOrder::model()->findByAttributes(array(
'order' => $this->id,
'group' => $group
));
if ($gofo) {
$gofo->delete();
$ovs = Ordervalues::model()->findAll('order = ' . $this->id . ' AND field in (select id from ' . Orderfield::model()->tableName() . ' where ordergroup=' . $group . ')');
foreach ($ovs as $ov) {
if ($ov->field0->type == 2)
unlink(Yii::app()->getBasePath() . '/../files/' . $ov->id);
$ov->delete();
}
}
}
}
$status = ($status && $this->save());
return $status;
}
public function answer()
{
if ($this->remove) {
foreach ($this->remove as $id => $f) {
if ($f) {
$filemodel = Orderfiles::model()->findByAttributes(array(
'id' => $id,
'order_id' => $this->id
));
if ($filemodel) {
$filemodel->delete();
$path = Yii::app()->basePath . '/../files/answers/' . $id;
if (file_exists($path))
unlink($path);
}
}
}
}
$file = CUploadedFile::getInstance($this, 'file');
if ($file) {
$fm = new Orderfiles('insert');
$fm->name = $file->name;
$fm->size = $file->size;
$fm->order_id = $this->id;
if ($fm->save() && $this->save())
return $file->saveAs('files/answers/' . $fm->id);
return false;
}
return $this->save();
}
public function fill_in_fields()
{
$this->fields = array();
foreach ($this->ordervalues as $field) {
$f = $field->field0;
if (!isset($this->fields[$f->ordergroup]['active']))
$this->fields[$f->ordergroup]['active'] = true;
$this->fields[$f->ordergroup][$f->id] = $field->value;
}
}
public function getPrice()
{
return Yii::app()->db->createCommand('select sum(price) from ' . Ordergroup::model()->tableName() . ' where id in (select `group` from ' . GroupOfOrder::model()->tableName() . ' where `order` = ' . $this->id . ')')->queryScalar();
}
public function deleteTree()
{
$ovsff = Ordervalues::model()->findAll('`order` = ' . $this->id . ' AND field in (select id from ' . Orderfield::model()->tableName() . ' where type = 2)');
if ($ovsff) {
foreach ($ovsff as $value) {
$path = Yii::app()->getBasePath() . '/../files/' . $value->id;
if (file_exists($path))
unlink($path);
}
}
Ordervalues::model()->deleteAll('`order` = ' . $this->id);
GroupOfOrder::model()->deleteAll('`order` = ' . $this->id);
$status = true;
$ovsff = Orderfiles::model()->findAll('`order_id` = ' . $this->id); // files of answered orders
if ($ovsff) {
foreach ($ovsff as $value) {
$path = Yii::app()->getBasePath() . '/../files/answers/' . $value->id;
if (file_exists($path))
unlink($path);
$status = $status && $value->delete();
}
}
$trans = $this->trackCode;
$status = $this->delete();
$trans->delete();
return $status;
}
public function relations()
{
return array(
'orderfiles' => array(
self::HAS_MANY,
'Orderfiles',
'order_id'
),
'ordertype0' => array(
self::BELONGS_TO,
'Orderform',
'ordertype'
),
'trackCode' => array(
self::BELONGS_TO,
'Transaction',
'track_code'
),
'user0' => array(
self::BELONGS_TO,
'Users',
'user'
),
'ordervalues' => array(
self::HAS_MANY,
'Ordervalues',
'order'
),
'tickets' => array(
self::HAS_MANY,
'Ticket',
'order_id'
)
);
}
public function attributeLabels()
{
return array(
'id' => 'Code',
'name' => 'Name',
'start_date' => 'Date',
'finish_date' => 'End Date',
'status' => 'status',
'ordertype' => 'Type',
'user' => 'User',
'track_code' => 'Pay code',
'desc' => 'Description',
'file' => 'File'
);
}
public function getStatus()
{
$status = array(
0 => 'Waiting for pay',
1 => 'In progress',
2 => 'Completed',
3 => 'Draft'
);
return $status[$this->status];
}
public function getButton()
{
$status = array(
0 => 'Waiting for pay',
1 => 'In progress',
2 => 'Completed',
4 => 'Draft'
);
if ($this->status == 0) {
return CHtml::button('Pay', array(
'onclick' => 'window.location.href=\'' . Yii::app()->createUrl('financial/invoice', array(
'id' => $this->track_code
)) . '\''
));
}
return CHtml::button('Details', array(
'onclick' => 'window.location.href=\'' . Yii::app()->createUrl('service/order', array(
'id' => $this->id
)) . '\''
));
}
public function search()
{
$criteria = new CDbCriteria();
$criteria->compare('id', $this->id);
$criteria->compare('name', $this->name, true);
$criteria->compare('start_date', $this->start_date, true);
$criteria->compare('finish_date', $this->finish_date, true);
$criteria->compare('status', $this->status);
$criteria->compare('ordertype', $this->ordertype);
$criteria->compare('user', $this->user);
$criteria->compare('track_code', $this->track_code);
$criteria->compare('desc', $this->desc, true);
return new CActiveDataProvider($this, array(
'criteria' => $criteria
));
}
public static function model($className = __CLASS__)
{
return parent::model($className);
}
}
Related
Displaying success message after form is submitted
My form was working perfectly fine and displays the success message when the form is submitted. However, I just added a small piece of code and though the form submits, it doesn't display the success message anymore. This is my code: public function entrymarks() { $this->form_validation->set_error_delimiters('', ''); $this->form_validation->set_rules('exam_group_class_batch_exam_subject_id', 'Subject', 'required|trim|xss_clean'); if ($this->form_validation->run() == false) { $data = array( 'exam_group_class_batch_exam_subject_id' => form_error('exam_group_class_batch_exam_subject_id'), ); $array = array('status' => 0, 'error' => $data); echo json_encode($array); } else { $exam_group_student_id = $this->input->post('exam_group_student_id'); $insert_array = array(); $update_array = array(); if (!empty($exam_group_student_id)) { foreach ($exam_group_student_id as $exam_group_student_key => $exam_group_student_value) { $attendance_post = $this->input->post('exam_group_student_attendance_' . $exam_group_student_value); if (isset($attendance_post)) { $attendance = $this->input->post('exam_group_student_attendance_' . $exam_group_student_value); } else { $attendance = "present"; } $cal1 = $this->input->post('exam_group_student_ca1_' . $exam_group_student_value); $cal2 = $this->input->post('exam_group_student_ca2_' . $exam_group_student_value); $cal3 = $this->input->post('exam_group_student_ca3_' . $exam_group_student_value); $cal4 = $this->input->post('exam_group_student_ca4_' . $exam_group_student_value); $exam = $this->input->post('exam_group_student_exam_' . $exam_group_student_value); $total = $cal1 + $cal2 + $cal3 + $cal4 + $exam; if ($total > 0) { // This line may be the problem $array = array( 'exam_group_class_batch_exam_subject_id' => $this->input->post('exam_group_class_batch_exam_subject_id'), 'exam_group_class_batch_exam_student_id' => $exam_group_student_value, 'attendence' => $attendance, 'get_ca1' => $cal1, 'get_ca2' => $cal2, 'get_ca3' => $cal3, 'get_ca4' => $cal4, 'get_exam' => $exam, 'get_tot_score' => $total, 'note' => $this->input->post('exam_group_student_note_' . $exam_group_student_value), ); $insert_array[] = $array; } } } $this->examgroupstudent_model->add_result($insert_array); $array = array('status' => '1', 'error' => '', 'message' => $this->lang->line('success_message')); echo json_encode($array); } } How do I get the success message to display again?
Prevent inserting to database If total value is equal to 0,
When adding scores for students, I would like those with a total score of 0 not to be inserted into the database at all. Controller: public function entrymarks() { $this->form_validation->set_error_delimiters('', ''); $this->form_validation->set_rules('exam_group_class_batch_exam_subject_id', 'Subject', 'required|trim|xss_clean'); if ($this->form_validation->run() == false) { $data = array( 'exam_group_class_batch_exam_subject_id' => form_error('exam_group_class_batch_exam_subject_id'), ); $array = array('status' => 0, 'error' => $data); echo json_encode($array); } else { $exam_group_student_id = $this->input->post('exam_group_student_id'); $insert_array = array(); $update_array = array(); if (!empty($exam_group_student_id)) { foreach ($exam_group_student_id as $exam_group_student_key => $exam_group_student_value) { $attendance_post = $this->input->post('exam_group_student_attendance_' . $exam_group_student_value); if (isset($attendance_post)) { $attendance = $this->input->post('exam_group_student_attendance_' . $exam_group_student_value); } else { $attendance = "present"; } $array = array( 'exam_group_class_batch_exam_subject_id' => $this->input->post('exam_group_class_batch_exam_subject_id'), 'exam_group_class_batch_exam_student_id' => $exam_group_student_value, 'attendence' => $attendance, 'get_ca1' => $this->input->post('exam_group_student_ca1_' . $exam_group_student_value), 'get_ca2' => $this->input->post('exam_group_student_ca2_' . $exam_group_student_value), 'get_ca3' => $this->input->post('exam_group_student_ca3_' . $exam_group_student_value), 'get_ca4' => $this->input->post('exam_group_student_ca4_' . $exam_group_student_value), 'get_exam' => $this->input->post('exam_group_student_exam_' . $exam_group_student_value), 'note' => $this->input->post('exam_group_student_note_' . $exam_group_student_value), ); $insert_array[] = $array; } } if ( intval($array['get_ca1'] +$array['get_ca2']+$array['get_ca3']+$array['get_ca4']+$array['get_exam'] ) > 0 ) { $this->examgroupstudent_model->add_result($insert_array); } } $array = array('status' => '1', 'error' => '', 'message' => $this->lang->line('success_message')); echo json_encode($array); } } I will like to first get the sum total of get_ca1+get_ca2+get_ca3+get_ca4+get_exam then if it is 0, don't insert. Please how do I do this?
I don't think you can access the array value on the fly without any workaround, and you've placed the insert outside the foreach. It would be best if you spent more time on these. Code Indexing Use proper IDE. Not like notepad. Debug all and every line for errors. Do like this. Since you're not using batch insert, you can do it one by one. $cal1 = $this->input->post('exam_group_student_ca1_' . $exam_group_student_value); $cal2 = $this->input->post('exam_group_student_ca1_' . $exam_group_student_value); $cal3 = $this->input->post('exam_group_student_ca1_' . $exam_group_student_value); $cal4 = $this->input->post('exam_group_student_ca1_' . $exam_group_student_value); $exam = $this->input->post('exam_group_student_ca1_' . $exam_group_student_value); $total = $cal1 + $cal2 + $cal3 + $cal4 + $exam; $array = array( 'exam_group_class_batch_exam_subject_id' => $this->input->post('exam_group_class_batch_exam_subject_id'), 'exam_group_class_batch_exam_student_id' => $exam_group_student_value, 'attendence' => $attendance, 'get_ca1' => $cal1, 'get_ca2' => $cal2, 'get_ca3' => $cal3, 'get_ca4' => $cal4, 'get_exam' => $exam, 'note' => $this->input->post('exam_group_student_note_' . $exam_group_student_value) ); if ($total > 0) { $this->examgroupstudent_model->add_result($array); } So final code will be public function entrymarks() { $this->form_validation->set_error_delimiters('', ''); $this->form_validation->set_rules('exam_group_class_batch_exam_subject_id', 'Subject', 'required|trim|xss_clean'); if ($this->form_validation->run() == false) { $data = array( 'exam_group_class_batch_exam_subject_id' => form_error('exam_group_class_batch_exam_subject_id'), ); $array = array('status' => 0, 'error' => $data); echo json_encode($array); } else { $exam_group_student_id = $this->input->post('exam_group_student_id'); $insert_array = array(); $update_array = array(); if (!empty($exam_group_student_id)) { foreach ($exam_group_student_id as $exam_group_student_key => $exam_group_student_value) { $attendance_post = $this->input->post('exam_group_student_attendance_' . $exam_group_student_value); if (isset($attendance_post)) { $attendance = $this->input->post('exam_group_student_attendance_' . $exam_group_student_value); } else { $attendance = "present"; } $cal1 = $this->input->post('exam_group_student_ca1_' . $exam_group_student_value); $cal2 = $this->input->post('exam_group_student_ca1_' . $exam_group_student_value); $cal3 = $this->input->post('exam_group_student_ca1_' . $exam_group_student_value); $cal4 = $this->input->post('exam_group_student_ca1_' . $exam_group_student_value); $exam = $this->input->post('exam_group_student_ca1_' . $exam_group_student_value); $total = $cal1 + $cal2 + $cal3 + $cal4 + $exam; $array = array( 'exam_group_class_batch_exam_subject_id' => $this->input->post('exam_group_class_batch_exam_subject_id'), 'exam_group_class_batch_exam_student_id' => $exam_group_student_value, 'attendence' => $attendance, 'get_ca1' => $cal1, 'get_ca2' => $cal2, 'get_ca3' => $cal3, 'get_ca4' => $cal4, 'get_exam' => $exam, 'note' => $this->input->post('exam_group_student_note_' . $exam_group_student_value) ); if ($total > 0) { $this->examgroupstudent_model->add_result($array); } } } } $array = array('status' => '1', 'error' => '', 'message' => $this->lang->line('success_message')); echo json_encode($array); }
Prestashop custom module draggable sort/order
Please tell me why I have a " Declaration of BlockRealization::updatePosition($way, $position, $id) should be compatible with ModuleCore::updatePosition($id_hook, $way, $position = NULL)" I have this code in module.php A similar question was here Prestashop custom admin module draggable sort/order not working? Under my code in module.php <?php if (!defined('_PS_VERSION_')) exit; class BlockRealization extends Module { protected $_html = ''; public function __construct() { $this->name = 'blockrealization'; $this->tab = 'front_office_features'; $this->version = '1.0.0'; $this->author = 'XXX'; $this->need_instance = 0; $this->ps_versions_compliancy = array('min' => '1.6', 'max' => _PS_VERSION_); $this->bootstrap = true; parent::__construct(); $this->displayName = $this->l('Module realization'); $this->description = $this->l('Display realization on homepage.'); $this->confirmUninstall = $this->l('Are you sure you want to uninstall?'); } public function install() { if (!parent::install() || !$this->registerHook('displayHeader') || !$this->registerHook('home') || !$this->createTables() ) return false; return true; } public function uninstall() { if (!parent::uninstall() || !$this->removeTable()) return false; return true; } protected function createTables() { /* Realization */ $res = (bool)Db::getInstance()->execute(' CREATE TABLE IF NOT EXISTS `'._DB_PREFIX_.'realization` ( `id_realization_slides` int(10) unsigned NOT NULL AUTO_INCREMENT, `image_realization` varchar(255) NOT NULL, `position` int(10) unsigned NOT NULL, PRIMARY KEY (`id_realization_slides`, `image_realization`) ) ENGINE='._MYSQL_ENGINE_.' DEFAULT CHARSET=UTF8; '); return $res; } protected function removeTable() { if (!Db::getInstance()->Execute('DROP TABLE `'. _DB_PREFIX_ . 'realization`')) return false; return true; } public function getContent() { $output = null; if (Tools::isSubmit('submit'.$this->name)) { $errors = ''; if ($_FILES) { $helper = new HelperImageUploader('realization_img'); $files = $helper->process(); if ($files) { foreach ($files as $file) { if (isset($file['save_path'])) { if (!ImageManager::checkImageMemoryLimit($file['save_path'])) $errors = Tools::displayError('Limit'); if (!$errors) { if (!ImageManager::resize($file['save_path'], dirname(__FILE__) . '/img/' . $file['name'])) $errors = Tools::displayError('error'); else { $previous_file = Configuration::get('realization_img'); $file_path = dirname(__FILE__) . '/img/' . $previous_file; if (file_exists($file_path)) unlink($file_path); $realization['image_realization'] = $file['name']; $realization['position'] = count($this->getAll()); if (!Db::getInstance()->insert('realization', $realization)) $errors = Tools::displayError('error'); } } unlink($file['save_path']); } } } } if ($errors) $output .= $this->displayError($errors); else $output .= $this->displayConfirmation($this->l('Settings updated')); } $output .= $this->generateList(); $output .= $this->displayForm(); return $output; } public function displayForm() { // Init Fields form array $fields_form[0]['form'] = array( 'legend' => array( 'title' => $this->l('Add the realization'), ), 'input' => array( array( 'type' => 'file', 'label' => $this->l('Image:'), 'name' => 'realization_img', 'hint' => $this->l('Upload image for contact:'), ) ), 'submit' => array( 'title' => $this->l('Save'), 'class' => 'btn btn-default pull-right' ) ); $helper = new HelperForm(); // Module, token and currentIndex $helper->module = $this; $helper->name_controller = $this->name; $helper->token = Tools::getAdminTokenLite('AdminModules'); $helper->currentIndex = AdminController::$currentIndex.'&configure='.$this->name; // Title and toolbar $helper->title = $this->displayName; $helper->show_toolbar = true; // false -> remove toolbar $helper->toolbar_scroll = true; // yes - > Toolbar is always visible on the top of the screen. $helper->submit_action = 'submit'.$this->name; $helper->toolbar_btn = array( 'save' => array( 'desc' => $this->l('Save'), 'href' => AdminController::$currentIndex.'&configure='.$this->name.'&save'.$this->name. '&token='.Tools::getAdminTokenLite('AdminModules'), ), 'back' => array( 'href' => AdminController::$currentIndex.'&token='.Tools::getAdminTokenLite('AdminModules'), 'desc' => $this->l('Back to list') ) ); // Load current value $helper->tpl_vars = array( 'fields_value' => array( 'realization_img' => Configuration::get('realization_img') ) ); return $helper->generateForm($fields_form); } public function generateList() { $content = $this->getAll(); $fields_list = array( 'id_realization_slides' => array( 'title' => 'ID', 'align' => 'center', 'class' => 'fixed-width-xs', ), 'image_realization' => array( 'title' => $this->l('Image'), 'orderby' => false, 'search' => false ), 'position' => array( 'title' => $this->l('Position'), 'position' => 'position' , 'orderby' => false, 'search' => false ), ); $helper = new HelperList(); $helper->shopLinkType = ''; $helper->actions = array('edit', 'delete'); $helper->module = $this; $helper->listTotal = count($content); $helper->identifier = 'id_realization_slides'; $helper->title = $this->l('Realizations'); $helper->table = $this->name; $helper->imageType = 'jpg'; $helper->orderBy = 'position'; $helper->orderWay = 'asc'; $helper->position_identifier = 'id_realization_slides'; $helper->token = Tools::getAdminTokenLite('AdminModules'); $helper->currentIndex = AdminController::$currentIndex.'&configure='.$this->name; return $helper->generateList($content, $fields_list); } public function getAll() { return Db::getInstance()->ExecuteS(' SELECT * FROM '._DB_PREFIX_.'realization '); } public function ajaxProcessUpdatePositions() { $way = (int)Tools::getValue('way'); $id_quicklinks = (int)Tools::getValue('id'); $positions = Tools::getValue('realization_slides'); if (is_array($positions)) foreach ($positions as $position => $value) { $pos = explode('_', $value); if (isset($pos[2]) && (int)$pos[2] === $id_velcroquicklinks) { if (isset($position) && $this->updatePosition($way, $position, $id_quicklinks)) echo 'ok position '.(int)$position.' for id '.(int)$pos[1].'\r\n'; else echo '{"hasError" : true, "errors" : "Can not update id '.(int)$id_quicklinks.' to position '.(int)$position.' "}'; break; } } } public function updatePosition($way, $position, $id) { if (!$res = Db::getInstance()->executeS(' SELECT `id_realization_slides`, `position` FROM `'._DB_PREFIX_.'realization` ORDER BY `position` ASC' )) return false; foreach ($res as $quicklinks) if ((int)$quicklinks['id_realization_slides'] == (int)$id) $moved_quicklinks = $quicklinks; if (!isset($moved_quicklinks) || !isset($position)) return false; return (Db::getInstance()->execute(' UPDATE `'._DB_PREFIX_.'realization` SET `position`= `position` '.($way ? '- 1' : '+ 1').' WHERE `position` '.($way ? '> '.(int)$moved_quicklinks['position'].' AND `position` <= '.(int)$position : '< '.(int)$moved_quicklinks['position'].' AND `position` >= '.(int)$position.' ')) && Db::getInstance()->execute(' UPDATE `'._DB_PREFIX_.'realization` SET `position` = '.(int)$position.' WHERE `id_realization_slides` = '.(int)$moved_quicklinks['id_quicklinks'])); } public function hookHome($params) { return $this->display(__FILE__, "views/templates/hook/realization.tpl"); }
Because you extend the class Module and it already has the same method which you basically override. And in PHP 7+ if you want to override or extend method you have to declare the same parameters(even if they have default values in the parent class method) and the same access level. So you just need to follow the rule and use the same declaration or you can rename your method if it's not necessary to override/extend the parent class one(and it seems so)
getting multiple customer details In codeigniter
i have written this code to receive data from the Android device. it was inserted just one customer data I need to receive multiple customer details if app goes offline. but it was inserting one data into DB in offline mode also.how can i change this for multiple customer data insertions. function index_post($customerID = false) { if ($customerID) { //update the record $updateData = array(); $allowedparams = array('streetid' => 'streetid', 'name' => 'name', 'mobile' => 'mobile', 'adhaar' => 'adhaar', 'profession' => 'profession', 'address' => 'address', 'pincode' => 'pincode', 'nearby' => 'nearby', 'paddress' => 'paddress', 'isOwned' => 'isOwned'); foreach ($allowedparams as $k => $v) { if (!$this->IsNullOrEmptyString($this->post($k, true))) { $updateData[$v] = $this->post($k, true); } } if ($this->model_customer->update($customerID, $updateData)) { $data = array('status' => true, 'messsage' => 'cusotmer updated succesfully'); $http_code = REST_Controller::HTTP_OK; } else { $data = array('status' => false, 'messsage' => 'cusotmer failed to update.'); $http_code = REST_Controller::HTTP_INTERNAL_SERVER_ERROR; } } else { //insert the record $allowedparams = array('streetid' => 'streetid', 'name' => 'name', 'mobile' => 'mobile', 'adhaar' => 'adhaar', 'profession' => 'profession', 'address' => 'address', 'pincode' => 'pincode', 'cycle' => 'cycle', 'nearby' => 'nearby', 'paddress' => 'paddress', 'isOwned' => 'isOwned'); $requiredParam = array('streetid', 'name', 'mobile', 'cycle'); $insertdata = array(); foreach ($allowedparams as $k => $v) { if (in_array($k, $requiredParam)) { //check if its not null if ($this->post($k) == null || trim($this->post($k)) == '') { $data = array('status' => false, 'message' => $k . ' parameter missing or empty'); $http_code = REST_Controller::HTTP_BAD_REQUEST; break; } } $insertData[$v] = $this->post($k, true); } if ($customerID = $this->model_customer->create($insertData)) { $data['customerID'] = $this->_frameCustomer2($this->model_customer->get($customerID)); //you need to put $http_code = REST_Controller::HTTP_OK; } else { $data = array('status' => false, 'message' => 'unable to create customer'); $http_code = REST_Controller::HTTP_INTERNAL_SERVER_ERROR; } } $this->response($data, $http_code); } private function _frameCustomer2($c) { //get value from index_get $data = array(); $data['id'] = $c->id; $data['name'] = $c->name; $data['street'] = array('id' => $c->streetid); $data['creationDate'] = $c->creationdate; $data['mobile'] = $c->mobile; $data['adhaar'] = $c->adhaar; $data['profession'] = $c->profession; $data['isOwned'] = ($c->isOwned == 1) ? true : false; $data['address'] = $c->address; $data['pincode'] = $c->pincode; $data['status'] = $c->status; $data['cycle'] = $c->cycle; $data['balance'] = $c->balance; $data['creditAvailable'] = $c->creditbalance; $data['nearby'] = $c->nearby; $data['accountNumber'] = $c->accountnumber; $data['permanentAddress'] = $c->paddress; $data['lastVisit'] = $this->model_customer->lastVisit($c->id); return $data; } and my part of model function is function create($insertdata = array()) { //new customer insert if ($this->db->insert('customer', $insertdata)) { return $this->db->insert_id(); } else { return false; } } function update($customerID = 0, $updateData = array()) { $this->db->where('id', $customerID); if ($this->db->update('customer', $updateData) && $this->db->affected_rows() == 1) { return true; } else { return false; }
Instead of customer Id, you can ask the mobile developers to send data in the form of array. In both online and offline. In case of online there will be just one element in the request array. function index_post() { $request_data = $this->request->body; foreach($request_data as $key => $value) { //Check if customer id is present if(Customer present) { Update the record } else { Insert the record } } }
Save as PDF in portrait orientation using Yii pdfGrid extension
Good Afternoon I am using the pdfGrid extension in Yii in which i am using the class EPDFGrid.. I am really confused on how to make the orientation in PORTRAIT mode. currently the rendered PDF file is in Landscape.. i tried changing this line public $orientation = 'L'; to 'P' but it did nothing.. i followed it here.. http://www.yiiframework.com/extension/pdf-grid/ is there an option in config that dictates the orientation into PORTRAIT.? can anybody help me.. this is the code in my EPDFGrid.php <?php Yii::import('zii.widgets.grid.CDataColumn'); Yii::import('ext.pdfGrid.fpdf.PDF'); class EPDFGrid extends CWidget { private $_debug = false; protected $_pdf; protected $_fill = false; protected $_columnWidths = array(); protected $_visibleColumns = 0; public $dataProvider; public $fileName; public $config = array(); public $columns = array(); public $labels = array(); public $orientation = 'L'; public $showTableOnEmpty = true; public $nullDisplay = ' '; public $emptyText; public $hideHeader = false; public function init() { if ($this->columns === array()) { if ($this->dataProvider instanceof CActiveDataProvider) $this->columns = $this->dataProvider->model->attributeNames(); else if ($this->dataProvider instanceof IDataProvider) { // use the keys of the first row of data as the default columns $data = $this->dataProvider->getData(); if (isset($data[0]) && is_array($data[0])) $this->columns = array_keys($data[0]); } } $id = $this->getId(); foreach ($this->columns as $i => $column) { if (is_string($column)) $column = $this->createDataColumn($column); else { if (!isset($column['class'])) $column['class'] = 'CDataColumn'; $column = Yii::createComponent($column, $this); } if (!$column->visible) { unset($this->columns[$i]); continue; } $this->_visibleColumns++; if ($column->id === null) $column->id = $id . '_c' . $i; $this->columns[$i] = $column; } $default = array( 'pdfSize' => 'A4', 'title' => '', 'subTitle' => '', 'headTitle' => '', 'amount' => '', 'tableWidth' => 275, 'rowHeight' => 6, 'colAligns' => null, 'colWidths' => null, 'showLogo' => false, 'imagePath' => YiiBase::getPathOfAlias('webroot') . '/images/logo.jpg', 'headerDetails' => false, ); $this->config = array_merge($default, $this->config); $this->_pdf = new PDF('L', 'mm', $this->config['pdfSize']); $this->_pdf->title = $this->config['title']; $this->_pdf->subTitle = $this->config['subTitle']; $this->_pdf->headTitle = $this->config['headTitle']; $this->_pdf->amount = $this->config['amount']; $this->_pdf->tableWidth = $this->config['tableWidth']; $this->_pdf->rowHeight = $this->config['rowHeight']; $this->_pdf->imagePath = $this->config['imagePath']; $this->_pdf->showLogo = $this->config['showLogo']; $this->_pdf->headerDetails = $this->config['headerDetails']; $this->_pdf->SetAligns($this->config['colAligns']); $this->_pdf->SetFont('Arial', 'B', 10); $this->_pdf->SetLineWidth(0.5); $this->_columnWidths = $this->_calcWidths(); $this->_pdf->SetWidths($this->_columnWidths); $this->_pdf->AliasNbPages(); $this->_pdf->AddPage(); foreach ($this->columns as $column) $column->init(); $this->renderItems(); } protected function createDataColumn($text) { if (!preg_match('/^([\w\.]+)(:(\w*))?(:(.*))?$/', $text, $matches)) throw new CException(Yii::t('zii', 'The column must be specified in the format of "Name:Type:Label", where "Type" and "Label" are optional.')); $column = new CDataColumn($this); $column->name = $matches[1]; if (isset($matches[3]) && $matches[3] !== '') $column->type = $matches[3]; if (isset($matches[5])) $column->header = $matches[5]; return $column; } protected function renderItems() { if ($this->dataProvider->getItemCount() > 0 || $this->showTableOnEmpty) { $this->renderTableHeader(); $this->renderTableBody(); } else $this->_renderEmptyText(); if ($this->_debug) Yii::app()->end(); else { // $this->_pdf->Output($this->fileName . ' (' . date('Y-m-d') . ').pdf', 'D'); $this->_pdf->Output($this->fileName . '.pdf', 'D'); exit(); } } protected function renderTableHeader() { if (!$this->hideHeader) { // Colores y fuente en negrita $this->_pdf->SetFillColor(245, 185, 120); $this->_pdf->SetTextColor(0); $this->_pdf->SetBold(); $rowHeader = array(); if ($this->labels != array()) { $rowHeader = $this->labels; } else { foreach ($this->columns as $i => $column) { if ($column->name == 'Id') { $rowHeader[] = strtoupper($column->name); } else { $rowHeader[] = $column->name; } // $rowHeader[] = $column->grid->dataProvider->model->getAttributeLabel($column->name); //$this->_pdf->Cell($this->_columnWidths[$i],$this->headerHeight,$data,0,0,'C',true); } } $this->_pdf->Row($rowHeader, array('fill' => true, 'header' => true)); } } protected function renderTableBody() { $data = $this->dataProvider->getData(); $n = count($data); // Restauraci�n de colores y fuentes $this->_pdf->SetFillColor(255, 242, 208); $this->_pdf->SetTextColor(0); $this->_pdf->SetFont(''); if ($n > 0) { for ($row = 0; $row < $n; ++$row) $this->renderTableRow($row); } else $this->_renderEmptyText(); } protected function renderTableRow($row) { //var_dump($this->dataProvider); $rowData = array(); foreach ($this->columns as $i => $column) { $data = $this->dataProvider->data[$row]; if ($column->value !== null) $value = $column->evaluateExpression($column->value, array('data' => $data, 'row' => $row)); else if ($column->name !== null) $value = CHtml::value($data, $column->name); // $rowData[] = $value===null ? $this->nullDisplay : $this->_formatString($value); $rowData[] = $value === null ? $this->nullDisplay : utf8_decode($value); } $this->_pdf->Row($rowData, array('fill' => $this->_fill)); $this->_fill = !$this->_fill; } protected function _renderEmptyText() { $emptyText = $this->emptyText === null ? Yii::t('zii', 'No results found.') : $this->emptyText; $this->_pdf->Cell(array_sum($this->_columnWidths), $this->config['rowHeight'], $emptyText, 0, 0, 'L'); } protected function _calcWidths() { $widths = array(); $params = $this->config['colWidths']; $visibleCols = $this->_visibleColumns; if (!$params) { $w = $this->_pdf->tableWidth / $visibleCols; for ($i = 0; $i < $visibleCols; $i++) $widths[] = $w; } else if (is_array($params)) { if (count($params) > $visibleCols) throw new Exception('La cantidad de parametros supera a las columnas visibles'); if (array_sum($params) > $this->_pdf->tableWidth) throw new Exception('La suma de los parametros supera a la longitud max de la tabla'); $nulls = 0; $confWidth = 0; for ($i = 0; $i < $visibleCols; $i++) { if (empty($params[$i])) $nulls++; else $confWidth += $params[$i]; } $w = $nulls ? ($this->_pdf->tableWidth - $confWidth) / $nulls : 0; for ($i = 0; $i < $visibleCols; $i++) { $widths[] = empty($params[$i]) ? $w : $params[$i]; } } else throw new Exception('El parametro $config[widths] debe ser un array'); return $widths; } protected function _formatString($string) { $string = strtolower(utf8_decode($string)); return ucwords($string); } protected function _combineColumns($print = '', $config = array()) { $default = array( 'from' => 0, 'to' => $this->_visibleColumns - 1, 'border' => 0, 'align' => 'L', 'fill' => $this->_fill, 'ln' => 1, ); $config = array_merge($default, $config); $b = $this->$config['border']; $a = $this->$config['align']; $f = $this->$config['fill']; $ln = $this->$config['ln']; $w = 0; for ($i = $this->$config['from']; $i <= $this->$config['to']; $i++) { $w += $this->_columnWidths[$i]; } $this->_pdf->Cell($w, $this->config['rowHeight'], $print, $b, $ln, $a, $f); if ($f) $this->_fill = !$this->_fill; } } this is the generated pdf file. <?php $data_provider = $model->viewEmployees($search, $from, $to); $data_provider->pagination = false; $this->widget('ext.pdfGrid.EPDFGrid', array( 'id' => 'employee-pdf', 'fileName' => 'Employees', 'dataProvider' => $model->viewEmployees($search, $from, $to), 'columns' => array( array('name' => 'ID Number','value' => '$data->company_id', 'htmlOptions'=>array('width'=>'10%'),), array('name' => 'Name', 'header' => 'Name', 'value' => '$data->getNameWithMiddleInitial()', 'htmlOptions' => array('width'=>'10%')), array('name' => 'Date Employed', 'value' => '$data->date_employed' ,'htmlOptions'=>array('width'=>'10%')), ), 'config' => array( 'title' => 'Sprasia Philippines Information Management System', 'subTitle' => 'List of Employees', 'headerDetails' => true, 'showLogo' => true, 'colAligns' => array('C', 'C', 'C'), ), )); ?> please help..
so silly of me.. i have found it. in this line.. $this->_pdf->AddPage(); i indicated P for portrait.. in which i have solved it by using this $this->_pdf->AddPage('P');