Joomla Language Filter Plugin & Changing a language field in the front end - joomla

I try to get the Releasemaker from Akeeba running and set the language for a release/item to All (*). But one can assume that this kind of problem should happen to any kind of code which tries to set a database field language using code in the Site folder.
If you have a multilingual site you probably have the plugin "System - Language Filter" running. This plugin sets a $_REQUEST['language'] value to a specific language. Every time. As a result code like $data = $app->input->getData() will get the language value of that $_REQUEST value instead of the value from the $_POST array so you can't set that language field with the usual ->bind($data) operation.
Did you encountered that issue as well? What is your solution for this?

I got myself a solution for this. I actually can imaging two ways to solve this. On the one hand you can rename the language parameter which is transferred from the client to the server and do magic stuff in the persistent layer. On the other hand you can try to fix the work of the language filter plugin. Since I don't want to change the component I chose the second way and added a system plugin to reset the language value in the request to * as I need it. Of course one can read that value from the POST data as well. The plugin is as strict as possible where to do that magic to not crash the other stuff.
class PlgSystemLanguagefixer extends JPlugin
{
public function onAfterRoute() {
// Get the application object.
$app = JFactory::getApplication();
$option = $app->input->get('option');
$format = $app->input->get('format');
$task = $app->input->get('task');
$view = $app->input->get('view');
if ($option == 'com_ars' && $task=='save' && $format == 'json' && ($view=='releases' || $view='items')) {
$app->input->set('language', '*');
}
}
}
Please note that this question is still open for better answers :)

Related

Laravel 5.4 : Dynamic validation rule

I kind of struggle to find the answer to my question, and my test don't prove to be useful. So maybe someone here would have hit the same issue that I'm facing.
I have inputs with the following kind of patterned name projects-0-1, project-0-2, project-1-0 and so on... These are file inputs so people can upload a document/an image.
So basically, I've been trying to get a validation message that would (ideally) be something like that:
$validator->getMessageBag()->add('project-*-*', 'File is empty!');
OR
$validator->getMessageBag()->add('project-*', 'File is empty!');
I tried a couple of things already and nothing seems to work.
The reason I get to add a custom message is that file is simply not validated if it comes empty to the $request object. So I first need to check if the $request->hasFile and in case it doesn't I want to add the error message.
Things to consider:
inputs can be dynamically added to the form, so I don't know the exact number of file inputs I need to validate beforehand.
even if this should not impact the code and validation, it's worth noticing that everything happens through ajax as I embed the form on another website. Therefore I created endpoints etc...
Any hint ?
Right, coming back here in case someone faces that issue too. I found a "hacky" way to get there and it does the trick for me.
As each input file is dynamically added to the DOM, I add an extra hidden input that holds the name of the file input as a value.
Then in my controller I do smth like that:
public function createValuesKeyArray ($preset)
{
$regexPattern = '/^'. $preset .'-[0-9]*$/';
$customPresets = preg_grep($regexPattern, array_keys(Input::all()));
$keys = [];
foreach ($customPresets as $customPreset) {
array_push($keys, $customPreset);
}
return $keys;
}
// This allows me to get all hidden input names in an array in order to get its value from the $request
$hiddenInputs = $this->createValuesKeyArray('hidden-project-name');
Once I get this array, I can do stuff like that and dinamycally add my set of rules for the input files present in the DOM:
foreach($hiddenInputs as $hiddenInput){
$globalRules[$request[$hiddenInput]] = 'required';
}
Not sure if this the right way to get there, but it does the job for me and I don't find that code horrible. I'll stick with it until I find a better way.

prevent duplicate value using ajax in sugar crm

i have create module using module builder , now i am having a field called as book Name
now if i give same book name 2 time t is accepting .
i don't want to use and plug in for checking duplicate value because i want to learn the customization through code .
so i can call ajax and check in data base weather the same book name is exist in db or not but i don't know how controller works in sugar crm . and how to call ajax in sugar crm .
can any one guide me , your help is much appreciated .
If you really want to accomplish this using ajax then I'd recommend an entryPoint as the way to go. This customization will require a couple of simple things. First you'll write a little bit of javascript to perform the actual ajax call. That ajax call will post to the entryPoint you write. The entryPoint will run the query for you and return a response to you in the edit view. So lets get started by writing the entryPoint first.
First, open the file custom/include/MVC/Controller/entry_point_registry.php. If the folder structure and file do not exist yet, go ahead and create them.
Add the following code to the entry_point_registry.php file:
$entry_point_registry['test'] = array('file' => 'custom/test.php', 'auth' => true);
Some quick explanation about that line:
The index value of test can be changed to whatever you like. Perhaps 'unique_book_value' makes more sense in your case. You'll see how this value is used in a minute.
The file value in the array points to where you're gonna put your actual code. You should also give this a more meaningful name. It does NOT need to match the array key mentioned above.
The 'auth' => true part determines whether or not the browser needs to have an active logged in session with SugarCRM or not. In this case (and almost all) I'd suggest keeping this to true.
Now lets look at the code that will go in custom/test.php (or in your case unique_book_name.php):
/* disclaimer: we are not gonna get all crazy with using PDO and parameterized queries at this point,
but be aware that there is potential for sql injection here. The auth => true will help
mitigate that somewhat, but you're never supposed to trust any input, blah blah blah. */
global $db; // load the global sugarcrm database object for your query
$book_name = urldecode($_REQUEST['book_name']); // we are gonna start with $_REQUEST to make this easier to test, but consider changing to $_POST when confirmed working as expected
$book_id = urldecode($_REQUEST['book_id']); // need to make sure this still works as expected when editing an existing record
// the $db->quote is an alias for mysql_real_escape_string() It still does not protect you completely from sql injection, but is better than not using it...
$sql = "SELECT id FROM book_module_table_name WHERE deleted = 0 AND name = '".$db->quote($book_name)."' AND id <> '".$db->quote($book_id)."'";
$res = $db->query($sql);
if ($db->getRowCount($res) > 0) {
echo 'exists';
}
else {
echo 'unique';
}
A note about using direct database queries: There are api methods you can use to accomplish this. (hint: $bean->retrieve_by_string_fields() - check out this article if you wanna go that route: http://developer.sugarcrm.com/2012/03/23/howto-using-the-bean-instead-of-sql-all-the-time/) However, I find the api to be rather slow and ajax should be as fast as possible. If a client asked me to provide this functionality there's a 99% chance I'd use a direct db query. Might use PDO and parameterized query if I'm feeling fancy that day, but it's your call.
Using the above code you should be able to navigate to https://crm.yourdomain.com/index.php?entryPoint=test and run the code we just wrote.
However at this point all you're gonna get is a white screen. If you modify the url to include the entryPoint part and it loads your home page or does NOT go to a white screen there are 3 potential causes:
You put something different for $entry_point_registry['test']. If so change the url to read index.php?entryPoint=whatever_you_put_as_the_array_key
You have sugar in a folder or something on your domain so instead of crm.yourdomain.com it is located somewhere ugly and stupid like yourdomain.com/sugarcrm/ if this is the case just make sure that your are modifying the url such that the actual domain portion is preserved. Okay I'll spell it out for you... https://yourdomain.com/sugarcrm/index.php?entryPoint=test
This is more rare, but for some reason that I cannot figure out apache sometimes needs to be reloaded when adding a new entrypoint. If you have shell access a quick /etc/init.d/apache2 reload should do the trick. If you don't have shell access you may need to open a ticket with your hosting provider (or get a fricking vps where you have some control!!!, c'mon man!)
Still not working? Did you notice the "s" in https? Try http instead and buy a fricking $9 ssl cert, geez man!
Okay moving on. Let's test out the entryPoint a bit. Add a record to the book module. Let's add the book "War of Art" (no, not Art of War, although you should give that a read too).
Now in the url add this: index.php?entryPoint=test&book_name=Art%20of%20War
Oh gawd that url encoding is hideous right! Don't worry about it.
You should hopefully get an ugly white screen with the text "exists". If you do let's make sure it also works the other way. Add a 2 to the book name in the url and hopefully it will now say "unique".
Quick note: if you're using Sugar you're probably also using mysql which is case insensitive when searching on strings. If you really need case sensitivity check out this SO article:
How can I make SQL case sensitive string comparison on MySQL?
Okay so now we have our entryPoint working and we can move on to the fun part of making everything all ajaxical. There are a couple ways to go about this, but rather than going the most basic route I'm gonna show you what I've found to be the most reliable route.
You probably will need to create the following file: custom/modules/CUSTOM_BOOK_MODULE/views/view.edit.php (I hope by now I don't need to point out changing that path to use your module name...
Assuming this file did not exist and we are starting from scratch here is what it will need to look like:
if(!defined('sugarEntry') || !sugarEntry) die('Not A Valid Entry Point');
class CUSTOM_BOOK_MODULEViewEdit extends ViewEdit
{
public function display()
{
// make sure it works in the subpanel too
$this->useForSubpanel = true;
// make the name value available in the tpl file
$this->ss->assign('name_value', $this->bean->name);
// load the parsed contents of the tpl into this var
$name_input_code = $this->ss->fetch('custom/modules/CUSTOM_BOOK_MODULE/tpls/unique_book_checker.tpl.js');
// pass the parsed contents down into the editviewdefs
$this->ss->assign('custom_name_code', $name_input_code);
// definitely need to call the parent method
parent::display();
}
}
Things are looking good. Now we gotta write the code in this file: custom/modules/CUSTOM_BOOK_MODULE/tpls/unique_book_checker.tpl.js
First a couple of assumptions:
We're going to expect that this is Sugar 6.5+ and jquery is already available. If you're on an earlier version you'll need to manually include jquery.
We're going to put the event listener on the name field. If the book name value that you want to check is actually a different field name then simply adjust that in the javascript below.
Here is the code for custom/modules/CUSTOM_BOOK_MODULE/unique_book_checker.tpl.js:
<input type="text" name="name" id="name" maxlength="255" value="{$name_value}" />
<span id="book_unique_result"></span>
{literal}
<script type="text/javascript">
$(document).ready(function() {
$('#name').blur(function(){
$('#book_unique_result').html('<strong> checking name...</strong>');
$.post('index.php?entryPoint=test', {book_name: $('#name').val(), book_id: $('[name="record"]').val()}, function(data){
if (data == 'exists') {
removeFromValidate('EditView', 'name');
addToValidate('EditView', 'name', 'float', true, 'Book Name Must be Unique.');
$('#book_unique_result').html('<strong style="color:red;"> ✗</strong>');
}
else if (data == 'unique') {
removeFromValidate('EditView', 'name');
addToValidate('EditView', 'name', '', true, 'Name Required');
$('#book_unique_result').html('<strong style="color:green;"> ✓</strong>');
}
else {
// uh oh! maybe you have php display errors on?
}
});
});
});
</script>
{/literal}
Another Note: When the code detects that the name already exists we get a little hacky and use Sugar's built in validation stuff to prevent the record from saving. Basically, we are saying that if the name already exists then the name value MUST be a float. I figured this is pretty unlikely and will do the trick. However if you have a book named 3.14 or something like that and you try to create a duplicate this code will NOT prevent the save. It will tell you that a duplicate was found, but it will not prevent the save.
Phew! Okay last two steps and they are easy.
First, open the file: custom/modules/CUSTOM_BOOK_MODULE/metadata/editviewdefs.php.
Next, find the section that provides the metadata for the name field and add this customCode attribute so that it looks like this:
array (
'name' => 'name',
'customCode' => '{$custom_name_code}',
),
Finally, you'll need to do a quick repair and rebuild for the metadata changes to take effect. Go to Admin > Repair > Quick Repair & Rebuild.
Boom! You should be good to go!

codeigniter_i18n multi language

I already read and follow the instruction from this link codeigniter_i18 multilanguage and it's works, but I have a little problem here, I don't know maybe at the routes config or the scripts.
for the example, this http://mysite.com is en default language in index of the site, but if I want to change different language for the instance dutch, so how to implement that I can get the url like this http://mysite.com/nl/
thanks in advance
Using it in the path like actually makes things a lot more complicated, because you ALWAYS need the first segment to be a country code (so you need to use /en for English)
An easier method to consider is to set a session variable when they select a language, and do it "in the background":
In your MY_Controller:
public function __construct()
{
parent::__construct();
$lang_code = ($this->session->userdata('lang_code'))? $this->session->userdata('lang_code'):'english';
$this->lang->load('project_launch', $lang_code);
$this->lang->load('project_launch_template', $lang_code);
$this->lang->load('project_launch_uploader', $lang_code);
}
function lang_select(){
$lang_code = $this->input->post('lang_code');
$this->session->set_userdata('lang_code', $lang_code );
}
and have your language selector (dropdown, little flags, whatever) call lang_select() to change the language & set the session variable; the construct will check the language each page load and load the appropriate language files

Extending Joomla 2.5 Banner Component

I really hope someone can help me.
I need to be able to serve banners in categories which are dependant on a session variable - and can't find a component which does that. So I'd like to extend the Joomla Banner component in order to select banners based on a session variable which contains the category path.
The correct session variable is being stored correctly.
In order to do this I added an option in the banners module .xml to allow for a session variable and the name of the session variable. This is being stored correctly in the module table within the params field along with the other module parameters.
Then I started on the
components > banners > com_banners > models > banners.php
by adding two lines of code in getListQuery where the SQL is assembled. They are:
$sess_vars = $this->getState('filter.sess_vars');
$sess_vars_name = $this->getState('filter.sess_vars_name');
But both variables contain nothing even though the ones the component already has can be retrieved fine. Without a doubt I need to change something somewhere else as well - but just can't figure out what to do.
Any help would be greatly appreciated.
The first thing to do is not hack the core files, hacking the core prevents you from using the built-in update feature to apply the regular bug fixes and security patches released by Joomla! (e.g. the recently released 2.5.9 version).
Rather make a copy of them and modify it so it's called something else like com_mybanners. Apart from the folder name and the entry point file (i.e. banners.php becomes mybanners.php) you will also want to update the components banners.xml to mybanners.php.(You will need to duplicate and modify both the front end /components/com_banners/ and /administrator/components/mybanners.php.)
Because of the way Banners work (i.e. banners are displayed in a module) you will also need to duplicate and modify /modules/mod_banners/,/modules/mod_banners/mod_banners.php and /modules/mod_banners/mod_banners.xml. Changing mod_banners to mod_mybanners in each location.
In Joomla! components the state is usually populated when JModel is instantiated, however, in this case the component is really about managing banners and recording clicks the display is handled by mod_banners. So, you will want to add some code to mod_mybanners.php to use the session variables you want to act on. Normally when a models state is queried you will collect the variables via JInput and add them to your object's state e.g.
protected function populateState()
{
$jApp = JFactory::getApplication('site');
// Load state from the request.
$pk = $jApp->input->get('id',0,'INT');
$this->setState('myItem.id', $pk);
$offset = $jApp->input->get('limitstart',0,'INT');
$this->setState('list.offset', $offset);
// Load the parameters.
$params = $app->getParams();
$this->setState('params', $params);
// Get the user permissions
$user = JFactory::getUser();
if ((!$user->authorise('core.edit.state', 'com_mycomponent')) && (!$user->authorise('core.edit', 'com_mycomponent')))
{
$this->setState('filter.published', 1);
$this->setState('filter.archived', 2);
}
}
The populateState() method is called when a state is read by the getState method.
This means you will have to change your copy of /components/com_banners/models/banner.php to capture your variables into the objects state similar to my example above.
From there it's all your own code.
You can find all of this information in the Developing a Model-View-Controller tutorial on the Joomla Doc's site

Page-specific logic in Joomla

I am trying to enable JavaScript in a Joomla template to behave differently depending on the page. In particular, I have set the Key Reference as that appears to be the most appropriate value I could find for this purpose. Unfortunately, I can't seem to access it in my code. I tried:
$this->params->get("keyref")
and a few other variations, but they simply returned a blank. How can I retrieve this value or is there a better way of writing page specific logic.
Related Articles
Joomla load script in a specific page: This would work, but seems like overkill for what I want to do here.
Each page can be given an alias. We can retrieve the alias using code from the forum:
function getCurrentAlias()
{
$menu = &JSite::getMenu();
$active = $menu->getActive();
return $active->alias;
}
We can then inject this into the Javascript:
var alias= '<?php echo getCurrentAlias(); ?>';
I'm not aware of keyref, but I would solve it by using the class suffix parameter you can set for each menu entry.see I would use a space in front of this suffix. With javascript you can then try to read this classname (suffix without the space) on each page.
getElementsByClassName("mysuffix");
for example
If this returns multiple objects, you know on which page you are. Will that help you?

Resources