Magento Order Comments - magento-1.7

And i have this form in the url link checkout/cart, and in this page i have a forms which has the following textbox of your name your email your telephone number your comments your company and your deadline project. In this form it works well and the data will send to email. I want that the your comments data will send to the admin panel in the sales/orders. Which is on this path app/design/adminhtml/default/default/template/sales/order/view info.phtml file.
I have found a sample code and im using it. And ive found out that the sample code im looking doesnt work out. This is the reference link im using
http://www.magecorner.com/magento-order-comments/
can someone help me figured this thing out? ive been stuck in here since last week
Any help is muchly appreciated

You can try this by using events. Add the below code to your config.xml. I hope you have an idea of dealing with observer and events.
<events>
<sales_order_place_after> <!-- identifier of the event we want to catch -->
<observers>
<sales_order_place_after_handler> <!-- identifier of the event handler -->
<type>model</type> <!-- class method call type; valid are model, object and singleton -->
<class>orderaudit/observer</class> <!-- observers class alias -->
<method>orderPlaced</method> <!-- observer's method to be called -->
<args></args> <!-- additional arguments passed to observer -->
</sales_order_place_after_handler>
</observers>
</sales_order_place_after>
<sales_order_payment_capture> <!-- identifier of the event we want to catch -->
<observers>
<sales_order_payment_capture_handler> <!-- identifier of the event handler -->
<type>model</type> <!-- class method call type; valid are model, object and singleton -->
<class>orderaudit/observer</class> <!-- observers class alias -->
<method>paymentCapture</method> <!-- observer's method to be called -->
<args></args> <!-- additional arguments passed to observer -->
</sales_order_payment_capture_handler>
</observers>
</sales_order_payment_capture>
<sales_order_creditmemo_refund> <!-- identifier of the event we want to catch -->
<observers>
<sales_order_creditmemo_refund_handler> <!-- identifier of the event handler -->
<type>model</type> <!-- class method call type; valid are model, object and singleton -->
<class>orderaudit/observer</class> <!-- observers class alias -->
<method>creditmemoRefund</method> <!-- observer's method to be called -->
<args></args> <!-- additional arguments passed to observer -->
</sales_order_creditmemo_refund_handler>
</observers>
</sales_order_creditmemo_refund>
</events>
Step 2: Now add the following to Observer.php
public function orderPlaced(Varien_Event_Observer $observer)
{
if (Mage::getSingleton('admin/session')->isLoggedIn()) {
//if admin
$order = $observer->getEvent()->getOrder();
$user = Mage::getSingleton('admin/session');
$username = $user->getUser()->getUsername();
$comment = "Order placed by <strong>".$username."</strong>";
$order->addStatusHistoryComment($comment)
->setIsVisibleOnFront(false)
->setIsCustomerNotified(false);
$order->save();
}
else {
//placed by customer online
$order = $observer->getEvent()->getOrder();
$order->addStatusHistoryComment('Order placed online by customer')
->setIsVisibleOnFront(false)
->setIsCustomerNotified(false);
$order->save();
}
}
public function paymentCapture(Varien_Event_Observer $observer)
{
$invoice = $observer->getEvent()->getInvoice();
$order = $invoice->getOrder();
$user = Mage::getSingleton('admin/session');
$username = $user->getUser()->getUsername();
$comment = "Payment captured by <strong>".$username."</strong>";
$order->addStatusHistoryComment($comment)
->setIsVisibleOnFront(false)
->setIsCustomerNotified(false);
$order->save();
}
public function creditmemoRefund(Varien_Event_Observer $observer)
{
$creditmemo = $observer->getEvent()->getCreditmemo();
$order = $creditmemo->getOrder();
$user = Mage::getSingleton('admin/session');
$username = $user->getUser()->getUsername();
$comment = "Refund by <strong>".$username."</strong>";
$order->addStatusHistoryComment($comment)
->setIsVisibleOnFront(false)
->setIsCustomerNotified(false);
$order->save();
}
}

Related

Magento 2 Override Magento Checkout Model Cart updateItems function

I Need to Override updateItems function from \Magento\Checkout\Model\Cart
Also need to pass my custom helper class in __construct arguments . This is my __construct function of override class
namespace Vendor\Module\Model;
use Magento\Catalog\Api\ProductRepositoryInterface;
use Magento\Checkout\Model\Session;
Class Cart extends \Magento\Checkout\Model\Cart
{
public function __construct(\Magento\Framework\Event\ManagerInterface $eventManager,
\Magento\Framework\App\Config\ScopeConfigInterface $scopeConfig,
\Magento\Store\Model\StoreManagerInterface $storeManager,
\Magento\Checkout\Model\ResourceModel\Cart $resourceCart, Session $checkoutSession, \Magento\Customer\Model\Session $customerSession, \Magento\Framework\Message\ManagerInterface $messageManager, \Magento\CatalogInventory\Api\StockRegistryInterface $stockRegistry, \Magento\CatalogInventory\Api\StockStateInterface $stockState, \Magento\Quote\Api\CartRepositoryInterface $quoteRepository, ProductRepositoryInterface $productRepository,
\Vendor\Module\Helper\Data $helper, array $data = []
)
{
$this->helper = $helper;
parent::__construct($eventManager, $scopeConfig, $storeManager, $resourceCart, $checkoutSession, $customerSession, $messageManager, $stockRegistry, $stockState, $quoteRepository, $productRepository, $data);
}
}
After this i run setup:upgrade,compile, static content deploy commands. Also remove all folders in var. But when i pass the argument in __construct function. It is not working. It displays blank page. When i remove my arguments from __construct function. then page is loading.
If you want to override updateItems from checkout cart model class then you must add preference in your module di.xml file, something like this:
<?xml version="1.0"?>
<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:ObjectManager/etc/config.xsd">
<preference for="Magento\Checkout\Model\Cart" type="[Vendor_Name]\[Module_Name]\Model\Cart" />
</config>
then, your custom module app/code/[Vendor_Name]/[Module_Name]/Model/Cart.php should look like this:
<?php
namespace [Vendor_Name]\[Module_Name]\Model;
use Magento\Checkout\Model\Cart as MagentoCart;
use [Vendor_Name]\[Module_Name]\Helper\Data;
class Cart extends MagentoCart
{
protected $helper;
public function __construct(Data $helper)
{
$this->helper = $helper;
}
// Code ...
}
then compile dependencies and that's all. Read this article to know more about Overriding classes in Magento 2

update dynamically targeting provider in iPOJO

I have a component declared as:
<ipojo>
<component classname="HelloClass" name="helloCom" immediate="true">
<requires field="delayService" id="id1">
</requires>
</component>
<instance component="helloCom" name="hello">
<property name="requires.from">
<property name="id1" value="A"/>
</property>
</instance>
</ipojo>
The jar file of this component :helloComponent.jar
Now, i want to update (value="A") to (value="AA"). Thus, i implement a component using ConfigurationAdmin to update this property
public class ControllerReconfiguration {
private ConfigurationAdmin m_configAdmin;
#SuppressWarnings({ "rawtypes", "unchecked" })
public void reconfigure() throws IOException {
Configuration configuration = m_configAdmin.getConfiguration("hello","file:./helloComponent.jar");
configuration.setBundleLocation("file:./helloComponent.jar");
Properties props = new Properties();
//Dictionary props = new Hashtable();
props.put("id1", "AA");
configuration.update(props);
System.out.println("Update");
}
}
However, this ControllerReconfiguration component can't update the value 'A' (by 'AA') in 'hello' instance.
How to modify this ControllerReconfiguration component, please ?
Thanks you for your help.
Unfortunately, you can't push new 'from' configuration like this.
However, you can use the iPOJO introspection API directly: http://felix.apache.org/documentation/subprojects/apache-felix-ipojo/apache-felix-ipojo-userguide/ipojo-advanced-topics/using-ipojo-introspection-api.html
Retrieve the Architecture service of the instance
Retrieve the InstanceDescription and DependencyDescription
Call the setFilter method
Thanks Clement,
it works fine !!!!! :) I access InstanceManager using Factory.
Ex, in order to access InstanceManager of component "hello.call.CallHello"
#require
private Factory[] factories;
for (Factory factory : factories) {
/*
* "hello.call.CallHello" is a component name
* note: it is not component instance name
*/
if (factory.getName().equals("hello.call.CallHello")) {
/*
* a component can have many instances
* if there is only one instance.
* get(0) return the first instance.
*/
InstanceManager im = (InstanceManager) factory.getInstances().get(0);
}

Clear JSF form input values after submitting

If there's a form, and has a textbox and a button, how do you erase the content of the textbox after you submit the form?
<h:inputText id="name" value="#{bean.name}" />
<h:commandButton id="submit" value="Add Name" action="#{bean.submit}" />
After I enter a value in the textbox and submit, the value still appears in the textbox. I need to clear the content of the textbox once its been submitted. How can I achieve this?
Introduction
There are several ways to achieve this. The naive way is to simply null out the fields in backing bean. The insane way is to grab JS/jQuery for the job which does that after submit or even during page load. Those ways only introduces unnecessary code and indicates a thinking/design problem. All you want is just starting with a fresh request/page/view/bean. Like as you would get with a GET request.
POST-Redirect-GET
The best way is thus to just send a redirect after submit. You probably already ever heard of it: POST-Redirect-GET. It gives you a fresh new GET request after a POST request (a form submit), exactly as you intended. This has the additional benefit that the previously submitted data isn't re-submitted when the enduser ignorantly presses F5 afterwards and ignores the browser warning.
There are several ways to perform PRG in JSF.
Just return to same view with faces-redirect=true query string. Assuming a /page.xhtml, you could do so in action method:
public String submit() {
// ...
return "/page.xhtml?faces-redirect=true";
}
If you're still fiddling around with navigation cases the JSF 1.x way, then it's a matter of adding <redirect/> to the navigation case in question. See also How to make redirect using navigation-rule.
To make it more reusable, you can obtain the view ID programmatically:
public String submit() {
// ...
UIViewRoot view = FacesContext.getCurrentInstance().getViewRoot();
return view.getViewId() + "?faces-redirect=true";
}
Either way, if you've view parameters which needs to be retained in the request URL as well, then append &includeViewParams=true to the outcome. See also Retaining GET request query string parameters on JSF form submit.
If you're making use of some URL rewriting solution which runs outside JSF context, then you'd best grab the current request URL (with query string) and use ExternalContext#redirect() to redirect to exactly that.
public void submit() throws IOException {
// ...
ExternalContext ec = FacesContext.getCurrentInstance().getExternalContext();
StringBuffer requestURL = ((HttpServletRequest) ec.getRequest()).getRequestURL();
String queryString = ((HttpServletRequest) ec.getRequest()).getQueryString();
ec.redirect((queryString == null) ? requestURL.toString() : requestURL.append('?').append(queryString).toString());
}
It's only a mess which should really be refactored to some utility class.
Request/View scoped bean
Note that this all works only nicely in combination with request or view scoped beans. If you've a session scoped bean tied to the form, then the bean wouldn't be recreated from scratch. You've then another problem which needs to be solved as well. Split it into a smaller session scoped one for the session scoped data and a view scoped one for the view scoped data. See also How to choose the right bean scope?
Faces Messages
If you've a faces message to be shown as result of successful action, then just make it a flash message. See also How to show faces message in the redirected page.
public String submit() {
// ...
FacesContext context = FacesContext.getCurrentInstance();
context.addMessage(clientId, message);
context.getExternalContext().getFlash().setKeepMessages(true);
return "/page.xhtml?faces-redirect=true";
}
Ajax
Only if you happen to have an ajax-only page on which a F5 would always trigger a fresh new GET request, then simply nulling out the model field(s) in action method shouldn't harm that much.
See also:
How to navigate in JSF? How to make URL reflect current page (and not previous one)
Pure Java/JSF implementation for double submit prevention
You can blank out the property of the managed bean that should not be repainted when you render the response. This can be done done using code similar to the snippet posted below:
private String name;
public String getName(){return name;}
public void setName(String name){this.name=name};
public String submit()
{
//do some processing
...
// blank out the value of the name property
name = null;
// send the user back to the same page.
return null;
}
The reason for the current behavior can be found in how the JSF runtime processes requests. All JSF requests to a view are processed in accordance with the JSF standard request-response lifecyle. In accordance with the lifecyle, the managed bean contents are updated with the value from request (i.e. the value of DataForm.Name is set) before the application event (DataForm.submit) is executed. When the page is rendered in the Render Response phase, the current value of the bean is used to render the view back to the user. Unless the value is changed in an application event, the value will always be one that is applied from the request.
You can clear the form from the Bean method that gets called when the form is submitted;`
private String name;
private String description;
private BigDecimal price;
/*----------Properties ------------*/
/*-----Getter and Setter Methods---*/
public void save()throws SQLException{
String sql = "INSERT INTO tableName(name,description,price) VALUES (?,?,?)";
Connection conn = ds.getConnection();
try {
PreparedStatement pstmt = conn.prepareStatement(sql);
pstmt.setString(1, getName());
pstmt.setString(2, getDescription());
pstmt.setBigDecimal(3, getPrice());
pstmt.executeUpdate();
} catch (SQLException e) {
e.getMessage();
e.toString();
}finally{
conn.close();
clear();
}
}//End Save Method
public void clear(){
setName(null);
setDescription(null);
setPrice(null);
}//end clear`
Notice that the clear() method is called from the save method after all the operations of the save method is complete. As an option you could perform the clearing only if the methods operation was successful...The method below is placed in the ProductController Class...
public String saveProduct(){
try {
product.save();
} catch (SQLException e) {
e.printStackTrace();
}
return null;
}
The method call from the view/jsp would look like the Following:
<h:commandButton value="Save" action="#{productController.saveProduct}"/>
You can do it with jQuery.
I had the similar problem. I needed to clear popup window form.
<rich:popupPanel id="newProjectDialog" autosized="true"
header="Create new project">
<h:form id="newProjectForm">
<h:panelGrid columns="2">
<h:outputText value="Project name:" />
<h:inputText id="newProjectDialogProjectName"
value="#{userMain.newProject.projectName}" required="true" />
<h:outputText value="Project description:" />
<h:inputText id="newProjectDialogProjectDescription"
value="#{userMain.newProject.projectDescription}" required="true" />
</h:panelGrid>
<a4j:commandButton id="newProjectDialogSubmit" value="Submit"
oncomplete="#{rich:component('newProjectDialog')}.hide(); return false;"
render="projects" action="#{userMain.addNewProject}" />
<a4j:commandButton id="newProjectDialogCancel" value="Cancel"
onclick="#{rich:component('newProjectDialog')}.hide(); return false;" />
</h:form>
</rich:popupPanel>
jQuery code:
$('#newProjectForm').children('input').on('click', function(){$('#newProjectForm').find('table').find('input').val('');});
I added a code snippet how to reset all values for the current ViewRoot recursively for JSF 2 here:
Reset all fields in form
This works for submitted forms showing validation errors as well as for newly entered values in a form.

how to change the themes in asp.net mvc 2

I would like to have an option wherein a user can choose his theme for the site from the dropdown list and the theme applies to that page [atleast].
I want this to be done in ASP.NET MVC 2 without using jquery like frameworks.
How can this be accomplished.
I am using the default webforms viewengine and donot want to go for a custom viewengine for this purpose.
It seems this is not supported out of the box, but here's what I did to implement theming:
First, I Added the App_Themes folder to my project, and set up a couple of themes
I then decided to try and mimic the Web-forms profile provider as close as possible, and added a profile-property to web.config:
<profile>
<properties>
<add name="ThemePreference" type="string" defaultValue="Blue" />
</properties>
</profile>
So, basically what I wanted to do was to be able to load the different css's from the appropriate theme-folder when the theme changed. I did this by implementing a helper method attached to the UrlHelper class so that I could write:
<link href="#Url.Theme("~/Content/Site.css")" rel="stylesheet" type="text/css" />
This should then load the appropriate themed Site.css, and fall back to ~/Content/Site.css if no file was found.
The helper is pretty simple:
public static class UrlHelpers
{
public static string Theme(this UrlHelper url, string u)
{
if (u.StartsWith("~")) u = u.TrimStart('~');
SettingsProperty settingsProperty = ProfileBase.Properties["ThemePreference"];
return url.Content("~/App_Themes/"+settingsProperty.DefaultValue + u);
}
}
Now, in this version of the code it simply gets the default-value, so you'll need to tweak the code slightly. But as you can see, this is not limited to css-files, but works with everything from .master files to images.
Update - Using Session instead of profile
public static class UrlHelpers
{
public static string Theme(this UrlHelper url, string u)
{
if (u.StartsWith("~")) u = u.TrimStart('~');
object currentThemeName = null;
if (url.RequestContext.HttpContext.Session != null)
{
currentThemeName = url.RequestContext.HttpContext.Session["ThemePreference"];
}
return currentThemeName != null ? url.Content(String.Format("~/App_Themes/{0}{1}", currentThemeName, u)) : url.Content("~"+u);
}
}
The return-line in this method checks if it found a ThemePreference session-value, and then returnes the appropriate URL for the content requested, otherwise it simply returns the content as it was requested with no App_Theme prefix.
In your controlleraction for the DropDown postmethod, you'd simply do:
Session.Add("ThemePreference", whateverValueYouGotFromDropdown);
Update ends
With some tweaking and fixing, this should do the trick.
Hope it helps some, even though it's not a complete walkthrough :)

Applet on Browser

How I can use some functions that were declared on the applet class? i.e.
this is my class
public class hi extends JApplet{
public void HiThere(){
System.out.println("Hi on Java Console");
}
}
and on my browser it's declared something like:
<applet.... name="HI" id="HI" ......>Ooops!!!</applet>"
but when I tried to use the function there was a mistake, so how a can use the functions declared on my applet class?? Thanks!!!
First you should do this change to your code:
public class HI extends JApplet {
public HI() {System.out.println("Hi on Java Console");}
}
When you have done that, and your browser still has an error, then post the exact error message here. Also you might want to look for a tutorial "programming Java applets getting started", since your code tells me, that you don't seem to know what you are doing.
In order to call your class methods from js you must declare the <object> in html specifying a .jar or .class with your compiled content, the package of the main class and some other parameters like in the follow example (object is for IE, and embed is for FF):
I suppose that you want to invoke the hi.HiThere() method as defined in your question.
<object
width="100" height="100" id="hi">
<param name = "code" value = "path.to.your.main.class.hi">
<param name = "archive" value = "jar location">
<param name = "mayscript" value = "true">
<param name = "scriptable" value = "true">
...
<comment>
<embed
code = "path.to.your.main.class.hi"
archive = "your jar location"
scriptable = "true"
width = "100" height = "100"
name = "hi"
...
</embed>
</comment>
</object>
Then from the js you can access you object through the document using the id attribute in <object> or name in <embed> in the sample case document.hi. With the follow code you can invoke the HiThere(); method:
try{
// ie, ff
document.hi.HiThere();
}catch(Exception){
// chrome, safari, opera
document.hi[1].HiThere();
}
In order to execute with last java versions remember to meet the new java security requirements (manifest attributes http://docs.oracle.com/javase/tutorial/deployment/jar/manifestindex.html, jar signature... ).
You can call the applet methods in JavaScript:
To do this the applet should be launched from JavaScript, e.g.
<script src="https://www.java.com/js/deployJava.js"></script>
<script>
var attributes = { id: 'mainApplet', code:
'org.jazzteam.Example', archive: 'example.jar', width: 812, height:
635};
var parameters = {};
deployJava.runApplet(attributes, parameters, '1.7');
function actionInApplet(url) {
mainApplet.appletMethod(url);
}
</script>
In this case the applet is launched from JavaScript with id= 'mainApplet'. In the applet there is appletMethod() method, which we want to call. To do this you need to call the method related to JavaScript object with id name. You can also pass parameters to the called methods, as demonstrated in this example.
Also it is necessary to know that the applet method called from JavaScript should be privileged. To do this you need to wrap the method code in the following "wrapper":
AccessController.doPrivileged(new PrivilegedAction() {
public Object run() {
//method code
return new Object();
}
});
This information is taken from the article:
Frequently Asked Questions during Java applet development