how to post form and get data from database in opencart - opencart

how to post form and get posted data to controller and i don't know how to pass posted variable from controller to model after getting i want to pass variables to views
controller.php
if(isset($_POST["email"]))
{
$email=$_POST["email"];
}
$this->load->model('order/myorder');
$data['data1']=$this->model_order_myorder->getOrder($email) ;
view.php
foreach ($data1 as $row)
{
echo echo $row->order_id;
}
model.php
<?php
class ModelOrderMyorder extends Model {
public function getOrder($email) {
$sql = "SELECT * FROM ".DB_PREFIX."order,".DB_PREFIX."order_product WHERE ".DB_PREFIX."order.email='$email'";
$query = $this->db->query($sql);
return $query ;
}
}
Regards
Dev

You simply pass the value as the parameter, e.g.
$this->model_shipping_order->getordertracking($_POST['email']) {
You should also escape the parameter in your query to prevent SQL injection e.g.
WHERE email = '" . $this->db->escape($email) . "' ");

Related

Opencart Event system OC 3.0.2.0, override core controller and twig file?

Is it possible to use only the OC Event system for these overrides?
I need to override the core index function of the product controller. I want to edit the core file and add this line:
$data['quantity'] = $product_info['quantity'];
to the function index() in "class ControllerProductProduct extends Controller"
and then I need add this line in product.twig file:
<span>{{ quantity }}</span>
I want to use only the OC Event system, not ocmod or vqmod.
It is real?
Thanks for help.
First you need to add your event into database, you can use addEvent function inside your module install function, like this:
public function install(){
$this->load->model('setting/event');
$this->model_setting_event->addEvent('my_module', 'catalog/view/product/product/after', 'extension/module/my_module/edit_product_page');
}
Or add it manually:
INSERT INTO `oc_event` (`code`, `trigger`, `action`, `status`) VALUES ('my_module', 'catalog/view/product/product/after', 'extension/module/my_module/edit_product_page', 1);
Now create this file:
catalog\controller\extension\module\my_module.php
And its contents:
<?php
class ControllerExtensionModuleMyModule extends Controller {
public function edit_product_page(&$route = '', &$data = array(), &$output = '') {
if (isset ($this->request->get['product_id'])) {
$product_info = $this->model_catalog_product->getProduct($this->request->get['product_id']);
if ($product_info) {
// Display it before <li>Product Code:
$find = '<li>' . $data['text_model'];
$replace = '<li>Quantity: ' . $product_info['quantity'] . '</li>' . $find;
$output = str_replace($find, $replace, $output);
}
}
}
}
Result:
MacBook
Brands Apple
Quantity: 929
Product Code: Product 16
Reward Points: 600
Availability: In Stock

Add Tags to posts in ZF2

I am trying to implement Tags to my posts. the user will input the tags in a textbox separated by commas.
public function addAction() {
$entityManager = $this->getServiceLocator()->get('doctrine.entitymanager.orm_default');
$article = new Article;
$form = new ArticleForm();
$form->setHydrator(new DoctrineHydrator($entityManager,'CsnCms\Entity\Article'));
$form->bind($article);
$request = $this->getRequest();
if ($request->isPost()) {
$post = $request->getPost();
$form->setData($post);
if ($form->isValid()) {
$this->createTags($article, $post["Tags"]);
$this->prepareData($article);
$entityManager->persist($article);
$entityManager->flush();
return $this->redirect()->toRoute('csn-cms/default', array('controller' => 'article', 'action' => 'index'));
}
}
return new ViewModel(array('form' => $form));
}
in the above code i have added a class called createTags that i am planning to split the inputted tags into an array and create a new tag entity for each and then store the new tag entities in a array in the article object. Is this the correct way I should be doing this?
No, you wont be able search your pages based on tag if you store them in an array. you need to have a separated db table with columns like id,tag,pageId so you can properly search the pages with tag names.
Sorry if the question want that detailed was just wondering if I should use a filter instead (I think this would work but dont know if it is good practice)
In the end I just use the processData function
public function prepareData($article, $post) {
$separator = ",";
if($post['tagsString'] != "")
{
//Link Tags
$array = array_unique(explode($separator, $post['tagsString']));
foreach ($array as $tagString) {
$tag = $this->getEntityManager()->getRepository('Cms\Entity\Tag')->findOneBy(array('tag' => $tagString));
$link = new \Cms\Entity\LinkTagToArticle($article, $tagString, $tag);
$this->getEntityManager()->persist($link);
}
}
}

blank json array in symfony2

i am writing webservice in symfony2 but i facing some problem regarding the output ,as it is giving blank output.
class DefaultController extends Controller {
/**
*
* #Route("/webservices/activity/{id}", name="user_json_activity")
* #Method("get")
*/
public function activityAction($id) {
$em = $this->getDoctrine()->getEntityManager();
$list = $em->getRepository('FitugowebserviceBundle:activity')->findOneById($id);
$r_array = $this->routes2Array($list);
$r = array('activity' => $r_array);
return new Response(json_encode($r));
}
private function routes2Array($routes) {
$points_array = array();
foreach ($routes as $route) {
$r_array = array('activity' => $route->getActivity(),
'icon' => $route->getIcon());
$points_array[] = $r_array;
}
return $points_array;
}
}
When i try to fetch data for id=1 http://domain.org/fitugo/web/app_dev.php/webservices/activity/1 it is giving output as follows
{"activity":[]}
It look very strange that you want get array with findOneById method. The first thing I suggest to add a check that the entity founded by id exist. Then look that findOneById returns and check your controller logic.

Setting id in ember data with createRecord

If I try to create a record with something like
var myObject = App.ModelName.createRecord( data );
myObject.get("transaction").commit();
the id of myObject is never set.
This says that id generation should be handled by EmberData (first response). So what should be happening? Where is the new id determined. Shouldn't there be a callback to the API to get valid id?
ID is the primary key for your record which is created by your database, not by Ember. This is JSON structure submit to REST post, notice no ID.
{"post":{"title":"c","author":"c","body":"c"}}
At your REST Post function you must get the last insert ID and return it back with the rest of the model data to Ember using this following JSON structure. Notice the ID, that is the last insert ID. You must get that last insert ID manually using your DB api.
{"post":{"id":"20","title":"c","author":"c","body":"c"}}
This is my sample code for my REST post. I coded this using PHP REST Slim framework:
$app->post('/posts', 'addPost'); //insert new post
function addPost() {
$request = \Slim\Slim::getInstance()->request();
$data = json_decode($request->getBody());
//logging json data received from Ember!
$file = 'json1.txt';
file_put_contents($file, json_encode($data));
//exit;
foreach($data as $key => $value) {
$postData = $value;
}
$post = new Post();
foreach($postData as $key => $value) {
if ($key == "title")
$post->title = $value;
if ($key == "author")
$post->author = $value;
if ($key == "body")
$post->body = $value;
}
//logging
$file = 'json2.txt';
file_put_contents($file, json_encode($post));
$sql = "INSERT INTO posts (title, author, body) VALUES (:title, :author, :body)";
try
{
$db = getConnection();
$stmt = $db->prepare($sql);
$stmt->bindParam("title", $post->title);
$stmt->bindParam("author", $post->author);
$stmt->bindParam("body", $post->body);
$stmt->execute();
$insertID = $db->lastInsertId(); //get the last insert ID
$post->id = $insertID;
//prepare the Ember Json structure
$emberJson = array("post" => $post);
//logging
$file = 'json3.txt';
file_put_contents($file, json_encode($emberJson));
//return the new model back to Ember for model update
echo json_encode($emberJson);
}
catch(PDOException $e)
{
//$errorMessage = $e->getMessage();
//$data = Array(
// "insertStatus" => "failed",
// "errorMessage" => $errorMessage
//);
}
}
With some REST adapters, such as Firebase, you can define the id as a variable of the record you are going to create.
App.User = DS.Model.extend({
firstName: DS.attr('string')
});
var sampleUser = model.store.createRecord('user', {
id: '4231341234891234',
firstName: 'andreas'
});
sampleUser.save();
JSON in the database (Firebase)
"users": {
"4231341234891234": {
"firstName": "andreas"
}
}

Cakephp Geocoding Behaviour

I have been following this tutorial. Basically I want to take an address from a table I have and place that address on a google map. The tutorial seems pretty straight forward, create the table places, put the behavior in and model and what not.
Just kind of confused how I'd actually use that with my existing tables. I've read through the section in the cookbook about behaviors but am still a little confused about them. Mostly about how I'd integrate the tutorial into other views and controllers that aren't within place model?
first you need to add latitude / longitude coordinates to your address table...
you can do that with a writing parser around this google maps api call:
http://maps.google.com/maps/api/geocode/xml?address=miami&sensor=false
once your addresses contain the coordinates, all you need is to pass the coordinates
to a javascript google maps in your view, just copy the source :
http://code.google.com/apis/maps/documentation/javascript/examples/map-simple.html
here is a cakephp 2.0 shell to create latitude / longitude data
to run: "cake geo"
GeoShell.php :
<?php
class GeoShell extends Shell {
public $uses = array('Business');
public function main() {
$counter = 0;
$unique = 0;
$temps = $this->Business->find('all', array(
'limit' => 100
));
foreach($temps as $t) {
$address = $this->geocodeAddress($t['Business']['address']);
print_r($address);
if(!empty($address)) {
$data['Business']['id'] = $t['Business']['id'];
$data['Business']['lat'] = $address['latitude'];
$data['Business']['lng'] = $address['longitude'];
$this->Business->save($data, false);
$unique++;
}
}
$counter++;
$this->out(' - Processed Records: ' . $counter . ' - ');
$this->out(' - Inserted Records: ' . $unique . ' - ');
}
public function geocodeAddress($address) {
$url = 'http://maps.google.com/maps/api/geocode/json?address=' . urlencode($address) . '&sensor=false';
$response = #file_get_contents($url);
if($response === false) {
return false;
}
$response = json_decode($response);
if($response->status != 'OK') {
return false;
}
foreach ($response->results['0']->address_components as $data) {
if($data->types['0'] == 'country') {
$country = $data->long_name;
$country_code = $data->short_name;
}
}
$result = array(
'latitude' => $response->results['0']->geometry->location->lat,
'longitude' => $response->results['0']->geometry->location->lng,
'country' => $country,
'country_code' => $country_code,
'googleaddress' => $response->results['0']->formatted_address,
);
return $result;
}
}