Switching from multilang to default lang in codeigniter - codeigniter

We are using a multilanguage website like
www.example.com/en/ www.example.com/es/
we have roout config like this
$route['switch-language/language/(:any)'] = 'switch_language/language/$1';
$route['en/page/(:any)'] = 'page/view/$1';
$route['fr/page/(:any)'] = 'page/view/$1';
$route['es/page/(:any)'] = 'page/view/$1';
$route['pt/page/(:any)'] = 'page/view/$1';
We have a posiblity of turning off language switcher. When we turned off on url we have still www.example.com/en/ format.
Is there a way not showing language tag on the url when multilang switcher is turned off?
Language switcher controlles is like this
class Switch_language extends CI_Controller {
public function __construct() {
parent::__construct ();
}
function language($language = "") {
$this->load->model('template_model', '', TRUE);
$language = ($language != "") ? $language : "english";
$this->session->set_userdata ( 'site_lang', $language );
$language_iso = $this->template_model->get_language_iso2_from_language_key($language);
$this->session->set_userdata('site_lang_iso', strtolower($language_iso));
//redirect ( base_url () );
if(isset($_SERVER["HTTP_REFERER"])){
//redirect($_SERVER["HTTP_REFERER"]);
redirect ( base_url ().strtolower($language_iso) );
}
else{
redirect ( base_url () );
}
}
function language_code() {
if ($this->input->post ( 'language_save' )) {
$this->load->model('template_model', '', TRUE);
$language = $this->input->post ( 'language_key' );
$language = ($language != "") ? $language : "english";
$this->session->set_userdata ( 'site_lang', $language );
$language_iso = $this->template_model->get_language_iso2_from_language_key($language);
$this->session->set_userdata('site_lang_iso', strtolower($language_iso));
//redirect ( base_url () );
if(isset($_SERVER["HTTP_REFERER"])){
//redirect($_SERVER["HTTP_REFERER"]);
redirect ( base_url ().strtolower($language_iso) );
}
else{
redirect ( base_url () );
}
}
}
}
When i remove lang tags from route manually is ok. But need something automatic.
When turned off route would be
$route['page/(:any)'] = 'page/view/$1';
need some logic to solve this issue.

Related

How to redirect to another page in codeigniter from one page?

I have written a code in the controller which is given below. This code is for login page. In this code, the if statement notification is properly working but the else part is not working. It is not redirect to the url given in the redirect() instead it is showing a blank page. Can anyone tell y it is like that and correct it for me ? I have used header() function but also it is not working.I have placed all the code inside the 'kw' folder. This code is properly working in the localhost but when uploaded the same code to the live server, its not working.Is it due to version of the CI ?
<?php
if (!defined('BASEPATH'))
exit('No direct script access allowed');
class Login extends CI_Controller {
public function __construct() {
parent::__construct();
$this->load->library('session');
$this->load->library('validation');
$this->load->model('studentsmodel');
}
public function index() {
if (isset($_POST['submit']))
{
$post_data = array('stud_cin' => $this->input->post('stud_cin'),'stud_password' => $this->input->post('stud_password'),
);
$this->validation->set_data($post_data);
$this->validation->set_rules('stud_cin','Cin','required|trim');
$this->validation->set_rules('stud_password','Password','required|trim');
if ($this->validation->run() === FALSE)
{
}
else
{
$this->load->model("studentsmodel");
$this->load->helper('url');
$result = $this->studentsmodel->loginCheck($post_data);
if (!$result){
$this->notifications->notify('Wrong username/password; Login Failed','error');
}
else{
$this->session->set_userdata('student_id', $result['id']);
$this->session->set_userdata('stud_cin', $result['stud_cin']);
$this->session->set_userdata('stud_photopath', $result['stud_photopath']);
redirect('student/profile/edit/id/'.$this->session->userdata('student_id'),'refresh');
//header('location:http://www.website.com/kw/application/controller/student/profile/edit/id/$this->session->userdata("student_id")');
}
}
} $this->load->view("login");
}
}
profile controller edit function
public function index()
{
$student_id=$this->session->userdata('student_id');
$data['profile_data'] =$this->studentsmodel->get_Cinprofile($student_id);
$this->load->view("profileDetails.php", $data);
}
public function edit()
{
$uri = $this->uri->uri_to_assoc(4);
$student_id=$uri['id'];
if(isset($_POST['btn_submit']))
{
//echo "<pre>";print_r($_FILES);exit;
$img_val = $this->studentsmodel->getStudent_photo($student_id);
$photo_val = $img_val['stud_photopath'];
$photo_unlink = "";
if ($_FILES['stud_photopath']['name'] != "")
{
/*echo "in";exit;*/
$photo_chk = explode("photo/", $photo_val);
$photo_unlink = $photo_chk[1];
$photo_path = "";
$flag = "";
$f_type_chk = $_FILES['stud_photopath']['type'];
if ($f_type_chk != "image/gif" && $f_type_chk != "image/jpg" && $f_type_chk != "image/jpeg"
&& $f_type_chk != "image/bmp" && $f_type_chk != "image/png" && $f_type_chk != "")
{
$flag = "Select allowed file type and size for photo";
}
if ($_FILES['stud_photopath']['size'] >= 5242880) { $flag = "Select allowed file type and size for photo"; }
$target_path = getcwd() . "/public/photo/";
$db_path = "photo/";
if ($_FILES['stud_photopath']['name'] != '')
{
$file_name = $_FILES["stud_photopath"]["name"];
$file_size = $_FILES["stud_photopath"]["size"] / 1024;
$file_type = $_FILES["stud_photopath"]["type"];
$file_tmp_name = $_FILES["stud_photopath"]["tmp_name"];
$random = rand(111, 999);
$new_file_name = $random . $file_name;
$newfile_name=$cin."_". $file_name;
$upload_path = $target_path . $newfile_name;;
if (move_uploaded_file($file_tmp_name, $upload_path)) { $photo_path = addslashes($db_path . $newfile_name); } /*end if*/
else { $this->notifications->notify('Photo cannot upload', 'error'); }/*end else var_dump($this->validation->show_errors());*/
}/*end if $_FILES['photo']['name']*/
} /*END OF if ($_FILES['photo']['name'] != "") */
else { $photo_path = $photo_val; } /*END OF ELSE ($_FILES['photo']['name'] != "") */
$this->session->unset_userdata('stud_photopath');
$this->session->set_userdata('stud_photopath', $photo_path);
$data['photo_unlink'] = $photo_unlink;
/* echo $dob_dd = $this->input->post('dob_dd');exit;
$dob_mm = $this->input->post('dob_mm');
$dob_yy = $this->input->post('dob_yy');
$dob = $dob_dd . "-" . $dob_mm . "-" . $dob_yy;*/
$stud_age_dob =$this->input->post('stud_age_dob');
$timestamp = strtotime($stud_age_dob);
$dob = date('Y-m-d', $timestamp);
$validation_data = array(
'stud_name' => $this->input->post('stud_name'),
'stud_gender' => $this->input->post('stud_gender'),
'stud_age_dob' =>$this->input->post('stud_age_dob'),
'stud_mobile' => $this->input->post('stud_mobile'),
'stud_email' => $this->input->post('stud_email'),
);
//echo "<pre>";print_r($validation_data); exit;
$this->validation->set_data($validation_data);
$this->validation->set_rules('stud_name', 'Student Name', 'trim|alpha_space|required');
$this->validation->set_rules('stud_gender', 'Gender', 'required');
$this->validation->set_rules('stud_age_dob', 'DOB', 'required');
$this->validation->set_rules('stud_mobile', 'Mobile number', 'numeric|required');
$this->validation->set_rules('stud_email', 'Email Id', 'trim|required|valid_email|xss_clean');
if ($this->validation->run() === FALSE)
{ /* var_dump($this->validation->show_errors()); */ $this->notifications->notify('Please make all entries', 'error');}
else
{
$updation_data=array(
'stud_name' => $this->input->post('stud_name'),
'stud_gender' => $this->input->post('stud_gender'),
'stud_age_dob' => $this->input->post('stud_age_dob'),
'stud_gaurdian' =>$this->input->post('stud_gaurdian'),
'stud_mother' =>$this->input->post('stud_mother'),
'stud_mobile' => $this->input->post('stud_mobile'),
'stud_email' => $this->input->post('stud_email'),
'stud_tel' => $this->input->post('stud_tel'),
'stud_guardian_address' => $this->input->post('stud_guardian_address'),
'stud_pin' => $this->input->post('stud_pin'),
'stud_photopath' => $photo_path,
'stud_age_dob' => $dob
);
/*echo "<pre>";print_r($updation_data); exit; */
$update_status=$this->studentsmodel->update_profile($updation_data, $student_id);
if($update_status==1)
{
//$this->session->set_userdata('profile_status', 'Yes');
/*$this->session->userdata('profile_status');*/
redirect('student/profile/index/', 'refresh');
}
else
{
$this->notifications->notify('profile updted failed', 'error');
}
$data['profile_data']=$_POST;
}
$data['profile_data']=$_POST;
}
$data['profile_data']=$this->studentsmodel->get_Cinprofile($student_id);
$this->load->view("profile_edit.php",$data);
}
Check if you already load this helper
$this->load->helper('url');
This is the information about the redirect function
redirect($uri = '', $method = 'auto', $code = NULL);
Parameters:
$uri (string) URI string $method (string)
Redirect method (‘auto’,
‘location’ or ‘refresh’)
$code (string) HTTP Response code (usually 302 or 303)
Note:
Don't forget add in the config file the value for base_uri
https://www.codeigniter.com/user_guide/helpers/url_helper.html
https://www.codeigniter.com/userguide3/libraries/config.html
remove /id/ from your redirect()
redirect('student/profile/edit/'.$this->session->userdata('student_id'));

How know if an attribute in Magento use options

I want to know programmatically if a magento attribute use options or not to know if I must displayed this options.
For example a Text attribute don't use it and a Dropdown attributes have option. But how make programmatically this distinction ?
$product = Mage::getModel('catalog/product')->load($product_id);if($product->hasOptions){
$optionsArr = $product->getOptions();
foreach($optionsArr as $optionKey => $optionVal)
{
$options=array();
foreach($optionVal->getValues() as $valuesKey => $valuesVal)
{
$options[]=array("key"=>$valuesVal->getId(), "val"=>$valuesVal->getTitle());
}
$custom_option["titles"][]=array("title"=>$optionVal->getTitle(),"title_id"=>$optionVal->getId(),"options"=>$options);
//$optStr.= "</select>";
}
$attributeCode = 'code_here';
$attribute = Mage::getModel('eav/config')->getAttribute('catalog_product', $attributeCode);
if ($attribute->getSourceModel()) {
//it has options
} else {
//it does not have options
}
$attributeModel = Mage::getModel ( 'eav/entity_attribute' )->loadByCode ( 'catalog_product', 'attribute_code' );
if ($attributeModel->getData ( 'frontend_input' ) == 'select') {
$attribute = Mage::getSingleton ( 'eav/config' )->getAttribute ( 'catalog_product', 'attribute_code' );
if ($attribute->usesSource ()) {
$options = $attribute->getSource ()->getAllOptions ( false );
$ifoptionfound = false;
if($options)
$ifoptionfound = true;
}
}

Codeigniter switch language with multi-segment

I have no problem with using i18n in mydomain.com/en/controller
My problem begin if I used something like mydomain/foldername/en/controller
when I switch language it's coming like mydomain/foldername/en/ar/controller
as ar is the other language
my base_url is mydomain/foldername/
I believe that it coming from one index and i tried to change it in MY_LANG:
// Originaly CodeIgniter i18n library by Jérome Jaglale
// http://maestric.com/en/doc/php/codeigniter_i18n
//modified by Tobin Thomas
class MY_Lang extends CI_Lang {
/**************************************************
configuration
***************************************************/
// Add your languages here
private $languages = array(
'en' => 'english',
'ar' => 'arabic'
);
// special URIs (not localized)
private $special = array (
'admin',
'assets',
'editor'
);
// where to redirect if no language in URI
private $uri;
private $default_uri;
private $lang_code;
/**************************************************/
function MY_Lang()
{
parent::__construct();
global $CFG;
global $URI;
global $RTR;
$this->uri = $URI->uri_string();
$this->default_uri = $RTR->default_controller;
$uri_segment = $this->get_uri_lang($this->uri);
$this->lang_code = $uri_segment['lang'] ;
$url_ok = false;
if ((!empty($this->lang_code)) && (array_key_exists($this->lang_code, $this->languages)))
{
$language = $this->languages[$this->lang_code];
$CFG->set_item('language', $language);
$url_ok = true;
}
if ((!$url_ok) && (!$this->is_special($uri_segment['parts'][0]))) // special URI -> no redirect
{
// set default language
$CFG->set_item('language', $this->languages[$this->default_lang()]);
$uri = (!empty($this->uri)) ? $this->uri: $this->default_uri;
$uri = ($uri[0] != '/') ? '/'.$uri : $uri;
$new_url = $CFG->config['base_url'].$this->default_lang().$uri;
header("Location: " . $new_url, TRUE, 302);
exit;
}
}
// get current language
// ex: return 'en' if language in CI config is 'english'
function lang()
{
global $CFG;
$language = $CFG->item('language');
$lang = array_search($language, $this->languages);
if ($lang)
{
return $lang;
}
return NULL; // this should not happen
}
function is_special($lang_code)
{
if ((!empty($lang_code)) && (in_array($lang_code, $this->special)))
return TRUE;
else
return FALSE;
}
function switch_uri($lang)
{
if ((!empty($this->uri)) && (array_key_exists($lang, $this->languages)))
{
if ($uri_segment = $this->get_uri_lang($this->uri))
{
$uri_segment['parts'][0] = $lang;
$uri = implode('/',$uri_segment['parts']);
}
else
{
$uri = $lang.'/'.$this->uri;
}
}
return $uri;
}
//check if the language exists
//when true returns an array with lang abbreviation + rest
function get_uri_lang($uri = '')
{
if (!empty($uri))
{
$uri = ($uri[0] == '/') ? substr($uri, 0): $uri;
$uri_expl = explode('/', $uri, 2);
$uri_segment['lang'] = NULL;
$uri_segment['parts'] = $uri_expl;
if (array_key_exists($uri_expl[0], $this->languages))
{
$uri_segment['lang'] = $uri_expl[0];
}
return $uri_segment;
}
else
return FALSE;
}
// default language: first element of $this->languages
function default_lang()
{
$browser_lang = !empty($_SERVER['HTTP_ACCEPT_LANGUAGE']) ? strtok(strip_tags($_SERVER['HTTP_ACCEPT_LANGUAGE']), ',') : '';
$browser_lang = substr($browser_lang, 0,2);
return (!empty($browser_lang) && array_key_exists($browser_lang, $this->languages)) ? $browser_lang: 'en';
}
// add language segment to $uri (if appropriate)
function localized($uri)
{
if (!empty($uri))
{
$uri_segment = $this->get_uri_lang($uri);
if (!$uri_segment['lang'])
{
if ((!$this->is_special($uri_segment['parts'][0])) && (!preg_match('/(.+)\.[a-zA-Z0-9]{2,4}$/', $uri)))
{
$uri = $this->lang() . '/' . $uri;
}
}
}
return $uri;
}
}
// END MY_Lang Class
/* End of file MY_Lang.php */
/* Location: ./application/core/MY_Lang.php */
ANY IDEA?
i was facing the same behavior. The problem was not in MY_Lang. It was the call of $this->lang->switch_uri('lang') in the view. I do not used codeigniter functions like anchor, site_url to generate the right link. I used plain html. Small mistake, minutes/hours of code review.
<a href="<?php echo $this->lang->switch_uri('en'); ?>"><img ...
won't work. It adds lang segment twice to uri, instead use anchor or site_url
<a href="<?php echo site_url($this->lang->switch_uri('en')); ?>"><img ...

Why does this webform uploaded file via ajax throw an error in Drupal 7?

I have a webform and mymodule which alters it. The webform has a field stelle which gets populated based on the url query. For instance, if ?stelle=10 the field gets populated by the title of node with nid 10. If the query ?stelle is non-existant or followed by a nid which does not exist (is not of a certain content type) or does not contain a certain string the form will be redirecting to mynode?stelle=initiativ. The form has 2 fields to upload files via ajax, works good so far. Here is my code:
<?php
/**
* Altering the form! this will add class to the file upload/ remove buttons
*/
function mymodule_form_alter(&$form, &$form_state, $form_id) {
$conf = mymodule_defaults();
if ($form_id == 'webform_client_form_' . $conf['nid']) {
if (isset($form['submitted']['field1'])) {
$form['submitted']['field1']['#process'] = array('mymodule_my_file_element_process');
}
if (isset($form['submitted']['field2'])) {
$form['submitted']['field2']['#process'] = array('mymodule_my_file_element_process');
}
$nid = $form['#node']->nid;
$form['actions']['submit']['#ajax'] = array(
'callback' => 'mymodule_webform_js_submit',
'wrapper' => 'webform-client-form-' . $nid,
'method' => 'replace',
'effect' => 'fade',
);
$redirect_form = false;
$maintenance = false;
if (isset($form['submitted']['stelle']['#default_value']) && $form['submitted']['stelle']['#default_value'] !== '') {
$hide_components = array(
'einleitung_standard',
'einleitung_initiativ',
);
$unhide_components = array();
if ($form['submitted']['stelle']['#default_value'] == '') {
$redirect_form = true;
}
elseif (is_numeric($form['submitted']['stelle']['#default_value'])) {
$nid = $form['submitted']['stelle']['#default_value'];
$node = node_load($nid);
if ($node === false || (isset($node->type) && $node->type !== 'job')) {
$redirect_form = true;
}
else {
$type = $node->type;
if ($type == 'job') {
$form['submitted']['stelle']['#default_value'] = $node->title;
$form['submitted']['stelle']['#attributes']['disabled'] = 'disabled';
$form['submitted']['related']['#value'] = $nid;
$unhide_components = array(
'einleitung_standard'
);
}
}
}
elseif ($form['submitted']['stelle']['#default_value'] == 'initiativ') {
// unset($form['submitted']['stelle']);
$form['submitted']['related']['#value'] = 'initiativ';
$unhide_components = array(
'einleitung_initiativ'
);
}
}
else {
// $redirect_form = true;
// this causes an error
}
This is the weird part:
$redirect_form = false;
$maintenance = false;
if (isset($form['submitted']['stelle']['#default_value']) && $form['submitted']['stelle']['#default_value'] !== '') {
...
else {
// $redirect_form = true;
// this causes an error
}
When I active the line to redirect the form when the if condition is false, the button to upload a file via ajax throws an error alert on click (see bottom for error). To me, this looks like the form alter hook is being called again when the file upload button is clicked without having my field stelle available - is that right? How to fix this?
And now the rest of the module, basically just alterings:
else {
// $redirect_form = true;
// this causes an error
}
foreach ($unhide_components as $key => $component) {
if (is_array($component)) {
foreach ($component as $_key => $_component) {
$index = array_search($_component, $hide_components[$key]);
if ($index !== false) {
unset($hide_components[$key][$index]);
}
}
}
else {
$index = array_search($component, $hide_components);
if ($index !== false) {
unset($hide_components[$index]);
}
}
}
// hide
foreach ($hide_components as $k=>$hc1){
if (is_array($hc1)) {
foreach ($hc1 as $hc2) unset($form['submitted'][$k][$hc2]);
} else {
unset($form['submitted'][$hc1]);
}
}
if ($redirect_form) drupal_goto('node/'.$conf['nid'], array('query'=>array('stelle'=>'initiativ')), 301);
}
}
function mymodule_my_file_element_process($element, &$form_state, $form) {
$element = file_managed_file_process($element, $form_state, $form);
$element['upload_button']['#attributes'] = array('class' => array('button'));
$prefix = '<label class="browse-slave">';
$prefix .= '<span class="button">' . t('Choose a file') . '</span>';
$element['upload']['#prefix'] = $prefix;
$element['upload_button']['#prefix'] = '</label>';
$element['remove_button']['#attributes'] = array('class' => array('button'));
$element['remove_button']['#prefix'] = '</label>';
return $element;
}
function mymodule_webform_js_submit($form, $form_state) {
// define the $sid variable (submission id from webform)
$sid = $form_state['values']['details']['sid'];
// if we have a sid then we know the form was properly submitted, otherwise, we'll just return the existing $form array
if ($sid) {
// first we have to load up the webform node object
$node = node_load($form_state['values']['details']['nid']);
// create an array up with the confirmation message, retreived from the webform node
$confirmation = array(
'#type' => 'markup',
'#markup' => check_markup($node->webform['confirmation'], $node->webform['confirmation_format'], '', TRUE),
);
// return the confirmation message
return $confirmation;
}
else {
// return the form
return $form;
}
}
The AJAX error is something like described here. Changing server/php settings didnt help it.
Thanks!
The form builder (and any hook alters) will be run when a form is validated, which happens on #ajax actions.
I like to throw static custom data in $form['#someProperty'] so that it's available in the build, validate, and submit functions. Something like this should help you:
function mymodule_form_alter(&$form, &$form_state, $form_id) {
// ...
if (isset($_GET['stelle'])) {
$form['#stelle'] = $_GET['stelle']; // This will always be there.
}
// ...
}
Another option would be to throw the $node that you load in the form, like $form['#stelle_node'] = node_load(...) and obviously only do that when the nid is actually available to you, so that you don't overwrite it with empty data when the form builder runs again in the future.
When i was working with ajax in drupal 6 the hash symbol in url or request caused an error everytime..... so i replaced url with this
data.url.replace(/%2523/, '%23');

Codeigniter: Add a class to link if current_url() == href

Do you know of a way how to check if current_url() is equivalent to a link's href without using javascript? In doing so, if the href is the same then add class="active" to the link.
Edit: The first thing which comes to mind is making an array of all href values then using foreach to compare each one but maybe you have a better way than this?
Answer thanks to Nick Pyett:
if(!function_exists('anchor')){
function anchor($uri = '', $title = '', $attributes = '', $apply_active = FALSE){
if(!is_array($uri)){
$site_url = (!preg_match('!^\w+://! i', $uri)) ? site_url($uri) : $uri;
}
else {
$site_url = site_url($uri);
}
$title = (bool)$title ? $title : $site_url;
if($attributes != '') $attributes = _parse_attributes($attributes);
$active = $uri == uri_string() && $apply_active ? ' class="'.$apply_active.'"' : NULL;
return '<a href="'.$site_url.'"'.$attributes.$active.'>'.$title.'</a>';
}
}
You could extend the anchor function in the URL helper like this.
if ( ! function_exists('anchor'))
{
function anchor($uri = '', $title = '', $attributes = '', $apply_active = FALSE)
{
$title = (string) $title;
if ( ! is_array($uri))
{
$site_url = ( ! preg_match('!^\w+://! i', $uri)) ? site_url($uri) : $uri;
}
else
{
$site_url = site_url($uri);
}
if ($title == '')
{
$title = $site_url;
}
if ($attributes != '')
{
$attributes = _parse_attributes($attributes);
}
if ( $uri == uri_string() AND $apply_active )
{
$active = ' class="'.$apply_active.'"';
}
else $active = NULL;
return '<a href="'.$site_url.'"'.$attributes.$active.'>'.$title.'</a>';
}
}
I haven't tested this so check a look for bugs. Call the anchor function like this:
anchor('my_page', 'My Page', '', 'active');
See the docs for how to extend helpers: http://ellislab.com/codeigniter/user_guide/general/helpers.html
Edit: OK I've tested it and updated my answer so it should work well now.

Resources