Other way to pass data from block to controller Magento - magento

I'm pretty new to PHP programming and Magento. I wanna to pass the current ProductId from a form within a custom block to a controller (new action).
Yes I know that one method would be to add an input hidden (with my product id) in the custom block form and then to retrieve the Value through a regular:
$this->getRequest()->getPost('myvalue'))
Is there a better way in Magento to retrieve the value within the controller without having to declare extra secret input fields ?

Good for you for wanting to adhere to best practices within Magento! The passing of data to controllers is pretty standard, however. If we look at how the product is added from a product page, we'll actually see the product ID in the form action URL's parameters:
http://domain.com/checkout/cart/add/uenc/uenc_value/product/45573/
...where 45573 is the product ID. Of course this can also be sent to the controller via a hidden input field, which I use all the time. Note that the above is the same as http://domain.com/checkout/cart/add/?uenc=uenc_value&product=45573 in Magento.
Another way of storing data for use in controllers for future use is setting data into a session. For posting data to a controller I wouldn't recommend this method but it's something to keep in mind:
$session = Mage::getSingleton('core/session');
$session->setMyValue(true);
We can then retrieve the data from my_value later just by instantiating the session. Good luck!

Passing your data could be done in different ways :
You could use Magento's magic setters and getters.
So you would have to do this to set the value :
Mage::getSingleton('core/session')->setSomeVariable($value);
and this to retrieve it :
Mage::getSingleton('core/session')->getSomeVariable();
Or you could use the register.
Mage::register('key', $value); //to set your data
Mage::registry('key'); //to get your data

Magento provides a way to construct a URL with the necessary values, calculated against the configuration DOM. Blocks (and therefore block templates) can call Mage_Core_Block_Abstract::getUrl() directly:
$this->getUrl('some_handle/foo/test',array('id'=>'some_value'));
// Mage::getUrl() will work as well
The above would result in the following URL:
http://base_url/frontname/foo/action/id/some_value/
...which can be read in the FooController testAction() as
$this->getRequest()->getParam('id') // 'some_value'

Related

Passing data from one view to another in Laravel

I have a Controller that parses an XML and returns a view with a list of names and URLs.
return view('view_1',compact('myList'));
View_1 will have a form with parameters method="POST" action="goToView_2"
Then I get some information from my view_2 through a POST, but I still want to keep $myList so that view_2 view uses it aswell.
How do I pass $myList from the first view to the next through a controller?
It sounds like you're trying to have multi-step form of some kind.
I would store the data in the session and easily access it in the second controller or in the view (although not recommended).
https://laravel.com/docs/5.4/session#using-the-session
PS. I personally love using the global session helper.

Loading external data into Ember template using ember-data/DataStore

Here is what I'm tyrnig to do:
Make ajax request to retrieve JSON data from a PHP script
Insert that information into DataStore Models
Store those models within a controller
Display the information using {{#each}} with a handlebars template
Does ember-data have a built in way of retrieving data? If not, where
should the AJAX request be implemented?
What is the best way to insert the JSON data into the DS model?
What is the best way to then sync the models up with a Controller?
Any examples that implement all of the 4 steps would also be very helpful, since I can't seem to find any.
<edit>
Like I said in the comments, this questions asks a lot at once, so to follow up, here's a work in progress fiddle: http://jsfiddle.net/schawaska/dWcUp/
This is not 100%, but covers some of your questions. It uses the FixtureAdapter.
I'll be updating it as I find time.
</edit>
1 Make ajax request to retrieve JSON data from a PHP script
Ember-Data will take care of that for you. Consider the following:
window.App = Em.Application.create();
App.Store = DS.Store.extend({
revision: 12,
adapter: 'DS.RESTAdapter'
});
App.Product = DS.Model.extend({
name: DS.attr('string'),
imageUrl: DS.attr('string')
})
The code above defines a data store (almost like an ORM) within your client app. Ember uses convention over configuration (heavily), so as per configuration this code expects your backend to have a resource in the same domain as /products which talks to GET, POST, PUT and DELETE.
2 Insert that information into DataStore Models
Considering what I said above, by calling one of the following:
App.store.find(App.Product) or App.Product.find()
EmberData will fire a GET request through AJAX targeting your resource /products, and if you say App.Product.find(1), it will target /products/1.
Your app store will use its adapter and the adapter's serializer to translate the JSON result and materialize its data into your App.Product model.
3 Store those models within a controller
This is done when defining your application router. Regardless of what you do, Ember will run its own workflow, but it provides you several hooks, giving you the control of that specific action. Consider the following:
App.Router.map(function() {
this.resource('products');
});
App.ProductsRoute = Ember.Route.extend({
model: function() {
return App.Product.find();
}
});
The code above populates the model used in the products route (which you would access at http://yourdomain.com/#/products). Internally it will generate the code for your ProductsController, or you can define your own, which should extend ArrayController.
Controllers will have a content property which is an alias to the model or model collection. Again, convention over configuration.
4 Display the information using {{#each}} with a handlebars template
Providing you're following the conventions, in your handlebars template, you should iterate through your collection like this:
{{#each product in controller}}
{{#linkTo 'product' product}}
{{product.name}}
{{/linkTo}}
{{/each}}
Does ember-data have a built in way of retrieving data? If not, where
should the AJAX request be implemented?
Yes, simply call App.Product.find() for a product model and it return you a blank ModelArray while firing the AJAX request to the products resource in your backend, then materialize/populate your data into each model once it receives the data back from the server.
What is the best way to insert the JSON data into the DS model?
You shouldn't be concerned about this if you're using ember-data. The framework does that for you in most cases. That's why we love it. You might, however, have to configure mapping, namespace and plurals depending on your backend.
What is the best way to then sync the models up with a Controller?
Something similar to this:
var product = App.Product.createRecord({
name: 'laptop',
imageUrl: 'path/to/image.png'
});
product.save();
This should fire a POST or PUT request to your backend API.
You should definitely check:
http://emberjs.com/guides/
https://peepcode.com/products/emberjs
http://toranbillups.com/blog/archive/2013/01/03/Intro-to-ember-js-and-the-new-router-api/
Making the AJAX request
// Find all pets.
var pets = App.Pet.find();
// Find pet with ID of 1.
var pet = App.Pet.find(1);
Into DataStore Models
pets above will be a DS.RecordArray containing many App.Pet models, whereas pet is just one App.Pet.
Store in Controller
App.IndexRoute = Ember.Route.extend({
model: function() {
return App.Pet.find(4);
}
});
The router is used to setup the controller, and so we specify here that the IndexController should hold one App.Pet with the ID of 4. This can of course be dynamic. Since your controller represents only one model, it should be of the type ObjectController, but if it was used to store many pets, then it should be of the type ArrayController.
By specify the model, you will have access to it in your IndexController and index view (data-template-name="index"). This is because when you move into your index route, the IndexController is located/instantiated, IndexView is instantiated and placed into the DOM, all after consulting the IndexRoute for setting up the controller.
You can now do something like this in your template (although model. is not necessary): {{model.name}}, which will get you your pet's name.
Display using #each
Find all your pets using a modified version of the above code, but returning all of the pets. Remember, this is done by specifying no arguments to your find method:
App.IndexRoute = Ember.Route.extend({
model: function() {
return App.Pet.find();
}
});
Now we can do loop through all of the pets in the index template. Whilst there are many ways to loop, such as including content./model., excluding .content/model, using this, controller, et cetera..., it's not necessary, but that's for another day. What matters at the moment is that this will work for you, and will be the most self-intuitive:
{{#each pet in controller}}
{{pet.name}}
{{/each}}
I'll put together a jsFiddle for this if you would like. Please let me know.
Questions
Does ember-data have a built in way of retrieving data? If not, where
should the AJAX request be implemented?
Yes, that's Ember Data module which has some good guides on EmberJS.com.
What is the best way to insert the JSON data into the DS model?
Using Ember Data as per the examples up above.
What is the best way to then sync the models up with a Controller?
Using the model hook in the appropriate route to specify which model(s) your controller represents.

Symfony2 and filter, right strategy

I'm asking what is the best strategy for filtering with Symfony2.
I want to filter a table of entities (hotels). This filter should allow me to :
choose hotels with or whitout email, with or without web site etc.
choose hotels based on state and/or city (relation OneToMany)
choose what information I want to display on the table with checkboxs (for example display "email adress" on the hotel table, but do not display "tel" or "web site").
First I think to build the filter form on the HotelController. When the filter is submitted, I had a FlashBag for every $_POST sended, redirect to the same page, and if there are FlashBag I send cookies to the $reponse. Then I display the table filtered with data who are on the cookie.
But I dont't really like this, cause I had a very big indexAction() on the HotelController, and I think it'as not really clean to change $_POST to FlasBag to Cookie, is it ? I do this redirection, cause by refreshing the page, data are not posted again.
I'm also asking a question, to prevent a too big IndexAction() method, can I put some code to another method, for exemple a method PostToFlashBag() and another FlashBagToCookie(), or every method on a Controller has to end with the word "Action" and must be accessible with the router ?
Then, I think to another thing : had an entity "Filter", with every row I need. For exemple "WithEmail", "DisplayTel" etc.. Then I can build a FilterType easily, and update the Filter entitie, to redirect to the same page (again, to prevent reposting data if the user refreshes the page). Finally, I can display the table with the object Filter, with a method on the HotelRepository.
That seems great, but I'm a little worry because the filter entity will only have one entry, and I have to find the Filter(1). Due to MVC, is it correct to have a model with only one entry ?
What strategy would you choose (maybe another one) ? I'm interesting to learn good practice with MVC and Symfony2 devloppemnt.
Having a dedicated model class - let's call it Filter - that will receive the values input by the user, is definitely the way to go.
More over, use the Symfony2 form on this input, so you can have validation, and be sure that the withEmailis trully a boolean, etc. From you Filter, build you SQL/Doctrine query and return what your controller have to return, be it a view, or raw datas.
You can have any method you want in a controller. After all, controllers in Symfony2 are plain old PHP objects. They only have to implement ContainerAwareInterface. Usually they inherits Controller, but this inheritance only brings some proxy methods, like getDoctrine or render.
The only convention is that methods which are used as route must end with Action

friendly url in codeigniter with variables in url

I'm making a site using Codeigniter and my URL for a particular product page is like http://www.domain.com/products/display/$category_id/$product_id/$offset
$offset is used for limiting the number of pages shown per page when using the Codeigniter's Pagination library.
How I want to make it such that my URL is something more human friendly, like http://www.domain.com/$category_name/$product_name/$offset ie. http://www.domain.com/weapons/proton-canon/3
Can anyone point me the general approach? I just started learning codeigniter and is working on my first project
You can use what's generally known as a URL slug to achieve this.
Add a new field to your table, called "url_slug" or similar. Now you will need to create a slug for each product, and store it in this field.
CI has a function in the URL helper - url_title($string) which will take a string, and convert it for use in URL's.
For example My product name would become my_product_name.
Now, in your method, you can either - keep the product_id intact, use this as a parameter for your method to show specific products, and use the slug for human friendly links, or you can just use the url_slug to refer to products.
Your URL may look like:
www.domain.com/$category_name/$product_id/my_cool_product/$offset
or it could look like
www.domain.com/$category_name/my_cool_product/$offset
with no ID. the choice is yours, but the url_slug may change - the ID won't. Which may have SEO impacts.
Regardless, your method needs to look something like:
function display_product($product_id, $url_slug, $offset) {
// do what you gotta do...
}
You can then use URL's like the above.
You will need to use URI routing as well, as the example above will attempt to look for a controller called $category_name and a method called my_cool_product, which will of course not exist.
See URI Routing for further info.

Can I have multiple inputs in a form in CodeIgniter URL?

I know that CodeIgniter already elegantly handles URL's. What I have is a form with multiple elements (date, keyword, location = optional). Is it possible to set up CI to create a URL that looks like:
mysite.com/class/function/date/keyword?
If you are using CodeIgniter's form helper, it sends your form data via POST, so you can't easily have your field's value displayed in the url.
What you could have, though, is a controller method that collects your form data and redirects to the url you want.
If you need further clarification, please let me know.
Yes, you can use the anchor function by passing the relevant info to it.

Resources