laravel multi-language switch and change locale on load - laravel

I've implemented the language switch functionality following this post and it works perfectly but just when you click on the language switch, though I would like to change the locale and store it in the App when the page is loaded.
My function it's a bit different from the one in the post, I've added an else if just to make sure that the locale it's in the accepted languages
App/Middleware/Localization.php
public function handle($request, Closure $next)
{
$availableLangs = array('en', 'hu', 'pt', 'ro', 'sv');
$userLangs = substr($request->server('HTTP_ACCEPT_LANGUAGE'), 0, 2);
if (\Session::has('locale'))
{
\App::setlocale(\Session::get('locale'));
}
else if (in_array($userLangs, $availableLangs))
{
\App::setLocale($userLangs);
// Session::push('locale', $userLangs);
}
return $next($request);
}
How can I reuse this function or create a new function to achieve the same result but when you load the website?
I have a lot of route so I think that I will need a function in order to don't repeat the same code over and over.
I don't use the locale on the URL and I don't want to use it, so please don't propose a solution that includes that option.
Example of my URLS (each URL can be view with all the available languages)
domain/city1/
domain/city1/dashboard/
domain/city2/
domain/city2/dashboard/
domain/admin/
I don't want:
domain/city1/en/...
domain/city1/pt/...

Probably you need something like this, whenever the page load initially there won't be any server value so it cannot set value for the $userLangs variable. So as per your code, the if statement fails since there is no session value and the elseif condition also fails since there is no value set for $userLangs which cannot be found in the $availableLangs. Just add one else condition to set a default lanuage of the website when there is no prefered user language.
public function handle($request, Closure $next)
{
$availableLangs = array('en', 'hu', 'pt', 'ro', 'sv');
$userLangs = substr($request->server('HTTP_ACCEPT_LANGUAGE'), 0, 2);
if (\Session::has('locale'))
{
\App::setlocale(\Session::get('locale'));
}
else if (in_array($userLangs, $availableLangs))
{
\App::setLocale($userLangs);
Session::put('locale', $userLangs);
}
else {
\App::setLocale('en');
Session::put('locale', 'en');
}
return $next($request);
}

Related

Opening request value-based view without repeating code

I am trying to open different views based upon a request value. For example, if the value of $request is set to one, then view one should open. If the $request value is two, then view two should open.
My code is working fine, but right now, I will have to repeat code for each view. How can I do it without repeating the if condition?
Scenario
public function printreports(Request $request)
{
$reports = $request->get('reports');
if ($reports === 1) {
return view('teachers.report1', compact('anything'));
}
if ($reports === 2) {
return view('teachers.report2', compact('anything'));
}
}
For large amount of files with similar name pattern:
$viewName = sprintf('teachers.report%d', $request->get('reports', 1))
if (!\View::exists($viewName)) {
___ throw an error or return default view ____
}
return view($viewName, compact('anything'));

Magento product save, how to detect whether product data has been changed

While editting a product in the backend I need to know whether any of it's data has been changed or not?
$product->hasDataChanges() always return true even I didn't modify any fields.
Why does $product->hasDataChanges() always return true even I didn't modify any fields.?
Looking into the Varien_Object function setData function it appears that hasDataChanges is always set to true even if technically the data has not changes.
public function setData($key, $value=null)
{
$this->_hasDataChanges = true;
if(is_array($key)) {
$this->_data = $key;
$this->_addFullNames();
} else {
$this->_data[$key] = $value;
if (isset($this->_syncFieldsMap[$key])) {
$fullFieldName = $this->_syncFieldsMap[$key];
$this->_data[$fullFieldName] = $value;
}
}
return $this;
}
Solution:
When you have a model which is an type of Mage_Core_Model_Abstract, then you can easily get the previous data (original data) on save using public function getOrigData($key=null) method.
getOrigData() returns the data in the object at the time it was initialized/populated.
After the model is initialised you can update that data and getData() will return what you currently have in that object.
Have a look at Varien_Object (getOrigData,setOrigData) so you can have a look at how and why it is used.

How to retrieve $config['myConfig_array'] in Code Igniter

I've followed Codeigniter language and all seems to be setup as a hook.
function pick_language() {
require_once(APPPATH.'/config/language.php');
session_start();
// Lang set in URL via ?lang=something
if(!empty($_GET['lang']))
{
// Turn en-gb into en
$lang = substr($_GET['lang'], 0, 2);
$_SESSION['lang_code'] = $lang;
}
// Lang has already been set and is stored in a session
elseif( !empty($_SESSION['lang_code']) )
{
$lang = $_SESSION['lang_code'];
}
// Lang has is picked by a user.
// Set it to a session variable so we are only checking one place most of the time
elseif( !empty($_COOKIE['lang_code']) )
{
$lang = $_SESSION['lang_code'] = $_COOKIE['lang_code'];
}
// Still no Lang. Lets try some browser detection then
else if (!empty( $_SERVER['HTTP_ACCEPT_LANGUAGE'] ))
{
// explode languages into array
$accept_langs = explode(',', $_SERVER['HTTP_ACCEPT_LANGUAGE']);
log_message('debug', 'Checking browser languages: '.implode(', ', $accept_langs));
// Check them all, until we find a match
foreach ($accept_langs as $lang)
{
// Turn en-gb into en
$lang = substr($lang, 0, 2);
// Check its in the array. If so, break the loop, we have one!
if(in_array($lang, array_keys($config['supported_languages'])))
{
break;
}
}
}
// If no language has been worked out - or it is not supported - use the default
if(empty($lang) or !in_array($lang, array_keys($config['supported_languages'])))
{
$lang = $config['default_language'];
}
// Whatever we decided the lang was, save it for next time to avoid working it out again
$_SESSION['lang_code'] = $lang;
// Load CI config class
$CI_config =& load_class('Config');
// Set the language config. Selects the folder name from its key of 'en'
$CI_config->set_item('language', $config['supported_languages'][$lang]['folder']);
// Sets a constant to use throughout ALL of CI.
define('CURRENT_LANGUAGE', $lang);
}
Now when I try to access $config['supported_languages'] it returns null or errors. Why?

Magento Custom Router loading controller but nothing else

I'm trying to get some custom routing going on in Magento using the following code (which I've only slightly modified from here https://stackoverflow.com/a/4158571/1069232):
class Company_Modulename_Controller_Router extends Mage_Core_Controller_Varien_Router_Standard {
public function match(Zend_Controller_Request_Http $request){
$path = explode('/', trim($request->getPathInfo(), '/'));
// If path doesn't match your module requirements
if ($path[1] == 'home.html' || (count($path) > 2 && $path[0] != 'portfolios')) {
return false;
}
// Define initial values for controller initialization
$module = $path[0];
$realModule = 'Company_Modulename';
$controller = 'index';
$action = 'index';
$controllerClassName = $this->_validateControllerClassName(
$realModule,
$controller
);
// If controller was not found
if (!$controllerClassName) {
return false;
}
// Instantiate controller class
$controllerInstance = Mage::getControllerInstance(
$controllerClassName,
$request,
$this->getFront()->getResponse()
);
// If action is not found
if (!$controllerInstance->hasAction($action)) {
return false;
}
// Set request data
$request->setModuleName($module);
$request->setControllerName($controller);
$request->setActionName($action);
$request->setControllerModule($realModule);
// Set your custom request parameter
$request->setParam('url_path', $path[1]);
// dispatch action
$request->setDispatched(true);
$controllerInstance->dispatch($action);
// Indicate that our route was dispatched
return true;
}
}
The result is a page where the template has loaded but with no content. If I comment out the $this->loadLayout() / $this->renderLayout() in my controller I can print to screen. But when I try and load a Template and/or Block it breaks somewhere.
home.html also loads fine (as the method returns false if the path is home.html).
Any assistance would be greatly appreciated.
I was implementing something similar to this and came across the same problem(That makes sense, because I copypasted your code)
before $request->setDispatched(true);
I added $request->setRouteName('brands'); (brands is the frontname of my module).
And It worked.Don't know if It'll work for you, but definetely there was something missing so that magento didn't know what layout to apply, because I could tell that teh controller was being reached.

Codeigniter change database config at runtime

Can I change the database config per method in a controller?
$db['default']['db_debug'] = TRUE;
The default is TRUE, while I need to make it false in a certain method to catch the error and do something else (for example show 404 page).
When I tried $this->config->load('database') it fails.
Another question :
Can I check an incorrect query and catch it to some variables rather than displaying it to users other than setting the db_debug config to FALSE?
I checked the code of system/database/DB_Driver and found that:
$this->db->db_debug = FALSE;
will work in my controller to enable/disable the debug thing on the fly.
Expanding on the answer by comenk, you can extend the database class and implement various methods by which to achieve your goal.
First, you'll need to extend the core Loader class by creating a MY_Loader.php file
class MY_Loader extends CI_Loader
{
function __construct()
{
parent::__construct();
}
/**
* Load the Standard and/or Extended Database function & Driver class
*
* #access public
* #return string
*/
function database( $params = '', $return = FALSE, $active_record = NULL )
{
$ci =& get_instance();
if (class_exists('CI_DB') AND $return == FALSE AND $active_record == NULL AND isset($ci->db) AND is_object($ci->db))
{
return FALSE;
}
$my_db = config_item('subclass_prefix').'DB';
$my_db_file = APPPATH.'core/'.$my_db.EXT;
if(file_exists($my_db_file))
{
require_once($my_db_file);
}
else
{
require_once(BASEPATH.'database/DB'.EXT);
}
// Load the DB class
$db =& DB($params, $active_record);
$my_driver = config_item('subclass_prefix').'DB_'.$db->dbdriver.'_driver';
$my_driver_file = APPPATH.'core/'.$my_driver.EXT;
if(file_exists($my_driver_file))
{
require_once($my_driver_file);
$db = new $my_driver(get_object_vars($db));
}
if ($return === TRUE)
{
return $db;
}
// Initialize the db variable. Needed to prevent
// reference errors with some configurations
$ci->db = '';
$ci->db = $db;
}
}
By implementing the above this will allow you to create a MY_DB_mysqli_driver.php whereby mysqli is replaced by whatever driver you're using in your CI database.php config.
At this point you'd add comenk's answer to MY_DB_mysqli_driver.php
function debug_on() {
return $this->db_debug = TRUE;
}
function debug_off() {
return $this->db_debug = FALSE;
}
function in_error() {
return (bool) $this->_error_number();
}
Then in your model/controller,
$this->db->debug_off();
$this->db->query('SELECT * FROM `table`');
if( $this->db->in_error() ) {
show_404();
}
$this->db->debug_on();
you must add function on system/database/DB_driver.php
function debug_on()
{
$this->db_debug = TRUE;
return TRUE;
}
function debug_off()
{
$this->db_debug = FALSE;
return FALSE;
}
after that you can simply do this command to changes at run-time
$this->db->debug_off();
$this->db->reconnect();
$this->db->db_debug = 0; // 0: off, 1: on
That worx for me...
You can look at the $GLOBALS variable to locate this generic setting.
To hide bad SQL (and other errors) from users, you need to set the php error reporting level. CodeIgniter ships in basically development mode.
Go to index.php and replace this
error_reporting(E_ALL);
with this
error_reporting(0);
This is the quick way to do it. You can also implement this using a hook, so you don't have to touch CI files. You can also add logic to that hook so that it only sets it on the production server.
For debugging SQL, you can create a class that inherits from CI_Model, then create all your model classes to extend that class. In that class, you can add code for running queries that writes the queries to the log so that you can debug them easier. This won't help if the query itself is bad, but you should be able to figure that out before you get to that point.

Resources