What is the usage of observer.php in a module of magento - mysql

Actually I working now in magento for developing a module to check the voucher code used or not. The details are stored in a new table. In my config.xml, I specified the observer page for fetching the details from db table. But I don't know the exact use of observer page in magento. Can I use observer page for this usage.
But it proceed to an error
I checked the log file
which is
a:5:{i:0;s:203:"SQLSTATE[42000]: Syntax error or access violation: 1064 You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near '=' at line 1";i:1;s:1677:"#0 C:\wamp\www\Mymagento\lib\Varien\Db\Statement\Pdo\Mysql.php(110): Zend_Db_Statement_Pdo->_execute(Array)
My observer.php file is also shown below
class Module_Voucher_Model_Observer
{
public function __contruct()
{
$coupon_code = trim(Mage::getSingleton("core/session")->getData("coupon_code"));
}
public function getresultofVoucher($coupon_code)
{
$resource = Mage::getSingleton('core/resource');
$readConnection = $resource->getConnection('core_read');
$table = "voucher_code_status_table";
$query = 'SELECT * FROM ' . $table. 'WHERE value='.$coupon_code;
$results = $readConnection->fetchAll($query);
return $results;
}
}
Please help what is the mysql error here. Please help as soon as possible
Thanks in advance

Observer.php is a model class file, like all models this also can be called any were we need its function.
Normally we use observers when using magento events. In config.xml we declare events and we use observer functions to handle the event when it occurs.
I have gone through your error and code. It seems the code doesn't get the value of coupon code. Please check whether there is any value coming in $coupon_code.
That may be the issue.
Thanks.

An observer is an EventListener, events are dispatched in Magento with:
Mage::dispatchEvent('event_name', array('item' => $this));
When an event is dispatched, Magento will check which observers are bound to it, and will call the function defined in the config with a Varien_Event_Observer object as its parameter.
You're function could be something like this:
public function getresultofVoucher(Varien_Event_Observer $observer)
{
$item = $observer->getItem();
// do something with it
}

Related

Trying to update a column in database but NOT NULL attributes are not letting me update the values. I am using Laravel

I am trying to update the column with some other data but database table is not letting me update the table because of the NOT NULL constraints in it. I have this option of setting all the fields to NULL but I dont think that will be a good practice. Please I need a solution to it if anyone can help. I get the following error
Illuminate \ Database \ QueryException (HY000)
SQLSTATE[HY000]: General error: 1364 Field 'first_name' doesn't have a default value (SQL: insert into users (subject_id, updated_at, created_at) values (?, 2019-07-30 13:46:42, 2019-07-30 13:46:42))
Previous exceptions
SQLSTATE[HY000]: General error: 1364 Field 'first_name' doesn't have a default value (HY000)`
I have tried setting all the values to NULL and it worked but I want to work with some fields setting as NOT NULL and update the ones which are NULL and also if we can fetch or set the fields automatically to what we have ?
This is my controller where I am trying to update the field if this is required or help you understand my problem
public function deleteSubject($id) {
echo $id;
// die();
if(Auth::check()) {
$findSubject = Auth::user()->where('subject_id', $id);
$users = new User();
$users->subject_id = null;
$users->save();
// echo($findSubject);
// die();
Session::flash("message", "You subject has been deleted. You can add a new Subject now.");
return redirect('/subjects');
} else {
Session::flash("message", "Please sign in to access this page");
return redirect('/signup');
}
}
The following should work for your code. As it was said in the previous comment, it's because you try to create a new instance of a user without inserting value.
It look like you are trying to delete the subject associate with the authenticated user, so I suppose that you don't really need to create a new user, instead I think you should dissociate the user and the subject. So, the following should work for your code.
The purpose of that variant is to take the authenticated user and put a null value for the subject_id.
public function deleteSubject($id) {
echo $id;
// die();
if(Auth::check()) {
$user = User::where('subject_id', $id)->first(); // This will get the user that have the subect_id, but it's assuming that only one user have this subject_id.
// You can also do this just uncomment the first line below and comment the other one above.
// $user = User::find(Auth::user->id);
$user->subject_id = null;
$user->save()
Session::flash("message", "You subject has been deleted. You can add a new Subject now.");
return redirect('/subjects');
} else {
Session::flash("message", "Please sign in to access this page");
return redirect('/signup');
}
}
I think that you should take a look about how MVC work.
https://selftaughtcoders.com/from-idea-to-launch/lesson-17/laravel-5-mvc-application-in-10-minutes/
You should also take a look at relationship in Laravel: https://laravel.com/docs/5.8/eloquent-relationships
MVC and Eloquent-Relationships will help you understand some function in laravel to achieve this kind of goal really quickly.
If you get a User model and a Subject model, you can simply do something like this:
$user = User->find(Auth::user()->id);
$user->subjects()->dissociate($id);
I'm not sure, but I think the Auth facade let you use the user model function, so maybe this could work to:
Auth::user()->subjects()->dissociate($id);
You should also take a look at middleware: https://laravel.com/docs/5.8/middleware
With middleware, you can put rules like the one you are using to send a message to the user saying that he/she need to be log in to access the page into the middleware and reusing it whenever you need.

Set user permissions on each module in Yii2

I would like to set user permissions on each module.
Each module would have its table with the permissions. What is the most recommended way to do this?
Reason: My application has some optional modules for only a few clients.
UPDATE
Something like:
Table: mod_inventory_permission
id int
User_id int
Read_permission boolean
Write_permission boolean
Admin_permission boolean
You can use RBAC for it! you can set different modules in it and different permission for each module.
Yes you can do it by using Rbac which facilitate you to restrict user in same application to limited modules,controllers, or actions
You have to follow the following step i hope it will help you.
I suggest you to use the auth_ tables provided by yii2 for rbac
step 1: import all auth tables
step 2: Create different roles in auth_item tables with type = 1 and all permission with type = 2
Note
Please make sure you enter your permission in some specific pattern,i am using module/controller/action,
its up to you how you are going to implement it.
step 3: Create generic controller and extend all of your controller from this generic controller,
In your generic controller you have to check whether the user is allow to access the module,controller or action he/she want to access of not.
public function beforeAction($action) {
$module = Yii::$app->controller->module->id;
$controller = ucfirst(Yii::$app->controller->id);
$action = Yii::$app->controller->action->id;
if (Yii::$app->user->can($module)) {
if (Yii::$app->user->can($module . '/' . $controller)) {
return true;
}
if (Yii::$app->user->can($module . '/' . $controller . '/' . $action)) {
return true;
}
else {
throw new \yii\web\HttpException(403, 'You are not allowed to view this page');
}
} else {
throw new \yii\web\HttpException(403, 'You are not allowed to view this page');
}
}
The beforeAction function implement 3 layer authentication you can change it according to your requirements....
i hope it will help you

CakePHP SQL Error when trying to use loadModel

I have two controllers (Feeds & Items), on the Items add view, I want some information from the Feeds table visible to the user.
So in the Items Controller I'm trying to access the Feed model, everything I have come across recommends to use loadModel but when I try to load the Items add view, I getting the following error:
Error: SQLSTATE[42000]: Syntax error or access violation: 1064 You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near '' at line 1
SQL Query: SHOW TABLES FROM
Please note there is no relationship setup between these two tables.
Feed Model
App::uses('AppModel', 'Model');
class Feed extends AppModel {}
Item Model
App::uses('AppModel', 'Model');
class Item extends AppModel {}
Item Controller
App::uses('Feed','Model');
class ItemsController extends DirectResponseAppController {
function add() {
if ($this->request->is('post')) {
$this->Item->create();
if ($this->Item->save($this->request->data)) {
$this->Session->setFlash(__('Your item has been saved.'));
return $this->redirect(array('action' => 'index'));
}
$this->Session->setFlash(__('Unable to add your item.'));
} else {
$this->loadModel('Feed');
$xxx = $this->Feed->find('all');
}
}
}
Any help appreciated.
** EDIT **
After a bit more digging, the problem seems to be with this line:
$xxx = $this->Feed->find('all');
I'm just not sure why.
If your Feed is inside a plugin (DirectResponse), you must use loadModel like this:
$this->loadModel('DirectResponse.Feed');

How to show MySQL errors from a failed Modx/xPDO query object?

How do I show the error mysql throws when I try to insert data into a custom table and the insert fails?
For example, below a bit of code that should(will) fail with an SQL error.
$insert = "some insert sql statement that will fail";
$myquery = $modx->query($insert);
if(!$myquery){
echo 'error occurred! <br>';
}
How do I return what the error actually was [i.e. column mismatch, unique id exists etc.]?
There is a little bit easier way to track your custom xpdo request.
$c = $modx->newQuery('modResource');
$c->where(array(
'id1' => 1
));
// print request for control
print_r($c->toSQL());
$s = $c->prepare();
$s->execute();
print_r($s->errorInfo());
After execution we can catch an error:
Array ( [0] => 42S22 [1] => 1054 [2] => Unknown column 'modResource.id1' in 'where clause' )
It's all because xpdo use pdo and controls execution with it's help. Some code from xpdo source:
/**
* #see http://php.net/manual/en/function.pdo-errorinfo.php
*/
public function errorInfo() {
if (!$this->connect()) {
return false;
}
return $this->pdo->errorInfo();
}
Based on the examples in the xPDO Getting Started guide, $modx in this context appears to be a class extending PDO and the result resource object $myquery is likely a PDOStatement object.
You can therefore set an exception error mode on $modx as you would with a normal PDO object.
$modx->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
to force it to throw errors on failure. By default, PDO errors silently; its error modes are documented here.
Correction: Looking into the xPDO source it does not extend PDO, but rather contains a PDO object as a property and implement PDO methods, passing them through to its connection property. So the setAttribute() call will be passed through to the underlying PDO object and should work accordingly.
The xPDO constructor extends functionality from a normal PDO constructor slightly, and accepts an array of options in the 5th parameter where you may set the error mode, rather than setting it later via setAttribute():
$xpdo = new xPDO($dsn, $user, $password, [], [PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION]);
Whichever method you choose to set it, you may wrap your code in a try/catch block to catch exceptions of type PDOException on error:
try {
$insert = "some insert sql statement that will fail";
$myquery = $modx->query($insert);
}
catch (PDOException $e) {
echo 'error occurred! ' . $e->getMessage() . '<br>';
}
You may also more simply set the errormode to PDO::ERRMODE_WARNING and PHP will instead just emit E_WARNING messages, which unlike exceptions, are non-fatal.
I was able to verify all of this works as expected by setting up a quick test with xPDO.

CakePHP 2.4.2 Why is Cake using model names as SQL queries?

I have a fresh out o' the git repo CakePHP application. I just made a new model (Ingests) to track what data our system brings in. I wanted to make functions start() and end(), but end is protected so I switched to begin() and finish().
No matter what I do, CakePHP is trying to execute the model function names verbatim as the SQL queries. I have another model in this app that I've been working on this week that has not had this issue at all. Creating a new table/model today is when the problem appeared.
IngestsController.php
public function test(){
$this->autoRender = false;
//$result = $this->Ingest->finish();
$result = $this->Ingest->xyz();
debug($result);
}
Ingests.php Model
public function finish($id){
return 'giraffe';
}
public function xyz(){
return 'abc';
}
Output:
Error: SQLSTATE[42000]: Syntax error or access violation: 1064 You have an error
in your SQL syntax; check the manual that corresponds to your MySQL server
version for the right syntax to use near 'xyz' at line 1
SQL Query: xyz
I tried xyz() because there is no way xyz() could be a protected/not allowed function name... but apparently it's just as bad a choice as finish(). If I run the finish() function, I get the same output... "SQL Query: finish"
Check your file name, the name for your file name model should be Ingest.php instead of Ingests.php also check your class declaration:
<?php
App::uses('AppModel', 'Model');
class Ingest extends AppModel { //Make sure the model name is singular
public function finish($id){
return 'giraffe';
}
public function xyz(){
return 'abc';
}
}