ORM/Extra Validate iby two field - validation

Kohana 3.2
I want to check my parent_id but i need the second value of type_id.
Code:
public function rules()
{
return array(
'type_id' => array(
array('not_empty'),
array('digit'),
),
'parent_id' => array(
array('digit'),
array(array($this,'check_category'),array(':value', ':field','type_id'))
),
);
}
public function check_category($parent_id,$field,$type_id)
{
die($type_id);
}
How to sent two values of my field to my function ??
After i make that in my controller :
if(isset($_POST['submit']))
{
$data = Arr::extract($_POST, array('type_id', 'parent_id', 'name', 'comment'));
$category = ORM::factory('kindle_category');
$category->values($data);
try {
$extra_rules = Validation::factory($_POST)
->rule('parent_id','Kindle::check_category',array($data['type_id'],$data['parent_id'],'parent_id',':validation'));
$category->save($extra_rules);
$this->request->redirect('kindle/category');
}
catch (ORM_Validation_Exception $e) {
$errors = $e->errors('validation');
}
}
if($parent->type_id!=$type_id)
{
$validation->error($field, 'Dog name, not cat!');
return false;
}
How to see my error "Dog name,not cat!' in my View ?
Array errors doesnot have this value.

public function rules()
{
return array(
'type_id' => array(
array('not_empty'),
array('digit'),
),
'parent_id' => array(
array('digit'),
array(array($this,'check_category'),array(':validation'))
),
);
}
public function check_category($validation)
{
$type_id = $validation['type_id'];
...
}
http://kohanaframework.org/3.2/guide/orm/examples/validation

Related

Laravel - How to perform Advance Excel Import Validation Message using Maatwebsite

I am using Laravel-8 and Maatwebsite-3.1 package to import Excel into the DB using Laravel API as the endpoint.
Trait:
trait ApiResponse {
public
function coreResponse($message, $data = null, $statusCode, $isSuccess = true) {
if (!$message) return response() - > json(['message' => 'Message is required'], 500);
// Send the response
if ($isSuccess) {
return response() - > json([
'message' => $message,
'error' => false,
'code' => $statusCode,
'results' => $data
], $statusCode);
} else {
return response() - > json([
'message' => $message,
'error' => true,
'code' => $statusCode,
], $statusCode);
}
}
public
function success($message, $data, $statusCode = 200) {
return $this - > coreResponse($message, $data, $statusCode);
}
public
function error($message, $statusCode = 500) {
return $this - > coreResponse($message, null, $statusCode, false);
}
}
Import:
class EmployeeImport extends DefaultValueBinder implements OnEachRow, WithStartRow, SkipsOnError, WithValidation, SkipsOnFailure
{
use Importable, SkipsErrors, SkipsFailures;
public function onRow(Row $row)
{
$rowIndex = $row->getIndex();
if($rowIndex >= 1000)
return; // Not more than 1000 rows at a time
$row = $row->toArray();
$employee = Employee::create([
'first_name' => $row[0],
'other_name' => $row[1] ?? '',
'last_name' => $row[2],
'email' => preg_replace('/\s+/', '', strtolower($row[3])),
'created_at' => date("Y-m-d H:i:s"),
'created_by' => Auth::user()->id,
]);
public function startRow(): int
{
return 2;
}
}
Controller:
public function importEmployee(Request $request)
{
try {
$validator = Validator::make($request->all(), [
'document' => 'file|mimes:xls,xlsx|max:5000',
]);
if ($request->hasFile('document'))
{
if($validator->passes()) {
$import = new EmployeeImport;
$file = $request->file('document');
$file->move(public_path('storage/file_imports/employee_imports'), $file->getClientOriginalName());
Excel::import($import, public_path('storage/file_imports/employee_imports/' . $file->getClientOriginalName() ));
foreach ($import->failures() as $failure) {
$importerror = new ImportError();
$importerror->data_row = $failure->row(); // row that went wrong
$importerror->data_attribute = $failure->attribute(); // either heading key (if using heading row concern) or column index
$importerror->data_errors = $failure->errors()[0]; // Actual error messages from Laravel validator
$importerror->data_values = json_encode($failure->values());
$importerror->created_by = Auth::user()->id;
$importerror->created_at = date("Y-m-d H:i:s");
$importerror->save();
}
return $this->success('Employees Successfully Imported.', [
'file' => $file
]);
}else{
return $this->error($validator->errors(), 422);
}
}
} catch(\Throwable $e) {
Log::error($e);
return $this->error($e->getMessage(), $e->getCode());
}
}
I made it to SkipOnError and SkipOnFailure.
If there's error, it saves the error into the DB. This is working.
However, there is issue, if some rows fail it still display success (Employees Successfully Imported) based on this:
return $this->success('Employees Successfully Imported.
When there is partial upload, or all the rows or some of the rows have issues, I want to display this to the user. So that it will be interactive.
How do I achieve this?
Thanks

How to get the users detail info in api call in cs-cart?

I am trying to retrieve user information through api in CS-cart. But it returns only limited information. How can we modify the code to get all the user info for ex- user profiles, address, gst and all.
you can create your own API.
/var/www/html/app/addons/addon_name/Tygh/Api/Entities/Egg.php
<?php
namespace Tygh\Api\Entities;
use Tygh\Api\AEntity;
use Tygh\Api\Response;
class Egg extends AEntity
{
public function index($id = '', $params = array())
{
if(empty($id))
{
$dd=db_get_array("SELECT * FROM ?:table_name");
//result all rows
}
else
{
// for filtering purpose
$where=array("id"=>$id);
$dd=db_get_array("SELECT * FROM ?:table_name where ?w",$where);
//result-> specific one row
}
return array(
'status' => Response::STATUS_OK,
'data' => $dd
);
}
public function create($params)
{
return array(
'status' => Response::STATUS_OK,
'data' => array()
);
}
public function update($id, $params)
{
return array(
'status' => Response::STATUS_OK,
'data' => array()
);
}
public function delete($id)
{
return array(
'status' => Response::STATUS_NO_CONTENT,
);
}
public function privileges()
{
return array(
'index' => true,
'create' => 'create_things',
'update' => 'edit_things',
'delete' => 'delete_things',
'index' => 'view_things'
);
}
public function privilegesCustomer()
{
return array(
'index' => true
);
}
}
?>
Remarks:
file name,
class name,
file path
Or you can edit the user API entity from this location.
app/Tygh/Api/Entities/Users.php
Any doubts , then kick me in...

Magento invoice grid filter_condition_callback not working

I added a custom column to invoice grid using an observer.
The problem is that I can't sort or filter by the new column.
I added a filter condition callback but the function is not called.
Here is my Observer.php
class DB_CustomGrid_Model_Adminhtml_Observer
{
public function onBlockHtmlBefore(Varien_Event_Observer $observer)
{
$block = $observer->getBlock();
$payment_methods = array();
$readConnection = Mage::getSingleton('core/resource')->getConnection('core_read');
$query = 'SELECT method FROM '.Mage::getSingleton('core/resource')->getTableName('sales/order_payment').' GROUP BY method';
$methods = $readConnection->fetchAll($query);
foreach($methods as $payment) {
if($payment["method"] !== 'free') {
$payment_methods[$payment["method"]] = Mage::getStoreConfig('payment/'.$payment["method"].'/title');
}
}
switch ($block->getType()) {
case 'adminhtml/sales_invoice_grid':
$block->addColumnAfter('state', array(
'header' => Mage::helper('sales')->__('Payment Method'),
'index' => 'method',
'type' => 'options',
'width' => '70px',
'options' => $payment_methods,
'filter' => false,
'filter_condition_callback' => array($this, '_myCustomFilter'),
), 'method');
break;
}
}
public function beforeCollectionLoad(Varien_Event_Observer $observer)
{
$collection = $observer->getOrderInvoiceGridCollection();
$collection->join(array('payment'=>'sales/order_payment'),'main_table.order_id=parent_id',array('method'));
}
protected function _myCustomFilter($collection, $column)
{
exit;
if (!$value = $column->getFilter()->getValue()) {
return $collection;
}
$collection->getCollection()->getSelect()->where("sales_order_payment.method like ?", "%$value%");
return $collection;
}
}
I added an exit; to check if the function is called or not.
Try this:
Add a new protected function to your observer class:
protected function _callProtectedMethod($object, $methodName) {
$reflection = new ReflectionClass($object);
$method = $reflection->getMethod($methodName);
$method->setAccessible(true);
return $method->invoke($object);
}
Then call $block->sortColumnsByOrder() and the new function $this->_callProtectedMethod($block, '_prepareCollection') directly after $block->addColumnAfter();

How to use the same insert_id() in CodeIgniter from one function to another function [duplicate]

I have a problem with insert_id. I'm using CodeIgniter. I have a method in which I insert some values and in it I return
$insert_id=$this->db->insert_id();
return $insert_id;`
I want to use this value in another method in the same model. I tried that: $insert_id=$this->add_teacher_subject(); but in this way first method runs again and I doesn't receive last_insert_id , but this value +1. Please, tell me how could I solve this problem?
My model is:
public function add_teacher_subject() {
$date = new DateTime("now");
$data=array(
'teacher_id'=>$this->input->post('teacher'),
'user_id'=>$this->session->userdata['user_id'],
'created_at'=>$date->format('Y-m-d H:i:s')
);
$this->db->insert('student_surveys',$data);
$insert_id=$this->db->insert_id();
return $insert_id;
}
public function survey_fill()
{
$insert_id=$this->add_teacher_subject();
if ($this->input->post('answer')) {
$answers= $this->input->post('answer');
if (null !==($this->input->post('submit'))) {
$date = new DateTime("now");
foreach($answers as $question_id=>$answer)
{
$data = array(
'user_id'=>$this->session->userdata['user_id'],
'question_id'=>$question_id,
'answer'=>$answer,
'student_survey_id' => $insert_id
);
$this->db->insert('survey_answers', $data);
}
}
You can use SESSION[] for keeping last insert id:
public function add_teacher_subject() {
$date = new DateTime("now");
$data = array(
'teacher_id' => $this->input->post('teacher'),
'user_id' => $this->session->userdata['user_id'],
'created_at' => $date->format('Y-m-d H:i:s')
);
$this->db->insert('student_surveys', $data);
$insert_id = $this->db->insert_id();
$newdata = array('insert_id' => $insert_id);
$this->session->set_userdata($newdata);
return $insert_id;
}
public function survey_fill() {
$insert_id = $this->session->userdata('insert_id');
if ($this->input->post('answer')) {
$answers = $this->input->post('answer');
if (null !== ($this->input->post('submit'))) {
$date = new DateTime("now");
foreach ($answers as $question_id => $answer) {
$data = array(
'user_id' => $this->session->userdata['user_id'],
'question_id' => $question_id,
'answer' => $answer,
'student_survey_id' => $insert_id
);
$this->db->insert('survey_answers', $data);
}
}
}
}

can't Filter or search product in grid with custom renderer

I have a problem with filter in my module in admin grid.
I also used 'order_item_id' field in my custom table and fetching product name based on '(sales/order_item)' using renderer.
I also using " 'filter_condition_callback' => array($this, '_productFilter') " but it cant' work
My problem is: can't Filter for columns with custom renderer not working.
When i search product name in column,it returns zero records.
What i wrong in My Code ?
public function _prepareColumns()
{
$this->addColumn('entity_id', array(
'header' => Mage::helper('adminhtml')->__('ID'),
'align' =>'right',
'width' => '50px',
'index' => 'entity_id',
));
$this->addColumn('order_item_id', array(
'header' => Mage::helper('adminhtml')->__('Product Name'),
'align' =>'right',
'index' => 'order_item_id',
'renderer' => 'Test_Module1_Block_Adminhtml_Renderer_Product',
'filter_condition_callback' => array($this, '_productFilter'),
));
return parent::_prepareColumns();
}
protected function _productFilter($collection, $column)
{
if (!$value = $column->getFilter()->getValue()) {
return $this;
}
$this->getCollection()->getSelect()->where(
"order_item_id like ?
"
, "%$value%");
return $this;
}
my renderer is
class Test_Module1_Block_Adminhtml_Renderer_Product extends Mage_Adminhtml_Block_Widget_Grid_Column_Renderer_Abstract
{
public function render(Varien_Object $row)
{
$order = Mage::getModel('sales/order_item')->load($row->getData('order_item_id'));
return $order->getName();
}
}
It is because of you have rendered id and you are searching with product name. So you need to change your productfilter function and put code for search the id in table according to product name.
You need to change your function :
protected function _productFilter($collection, $column)
{
if (!$value = $column->getFilter()->getValue()) {
return $this;
}
$orderitem = Mage::getModel('sales/order_item')->getCollection();
$orderitem->addFieldToFilter('name',array('like'=>'%'.$value.'%'));
$ids =array();
foreach($orderitem as $item){
$ids[] = $item->getId();
}
$this->getCollection()->addFieldToFilter("id",array("in",$ids));
return $this;
}
I have done some changes on saumik code and its work for me.
protected function _productFilter($collection, $column)
{
if (!$value = $column->getFilter()->getValue()) {
return $this;
}
$orderitem = Mage::getModel('sales/order_item')->getCollection();
$orderitem->addFieldToFilter('name',array('like'=>'%'.$value.'%'));
$ids =array();
foreach($orderitem as $item){
$ids[] = $item->getOrderId(); // sales_flat_order_item.order_id = sales_flat_order.entity_id
}
$this->getCollection()->addFieldToFilter("entity_id",array("in",$ids));
return $this;
}

Resources