How i can on October CMS use translate plugin after extend new fields to user plugin? - translation

For my project i use User Plugin and Translate Plugin.
I've added custom new fields to the user and now I want to translate them.
I think I know why it does not work. But find no solution.
Somebody to have idea?
if i add to $model->translatable default fields like 'email', works fine.
i added boot function to my custom plugin with this code
\RainLab\User\Models\User::extend(function ($model) {
$model->implement[] = 'RainLab.Translate.Behaviors.TranslatableModel';
$model->translatable = ['about', 'preview_text'];
});

Hmm,
There is one problem. when you try to add it directly $model->translatable, It seems its treating it like attribute of model.
Try this $model->addDynamicProperty(variable_name, value);
\RainLab\User\Models\User::extend(function ($model) {
$model->implement[] = 'RainLab.Translate.Behaviors.TranslatableModel';
$model->addDynamicProperty('translatable', ['about', 'preview_text']);
// like this ^
});
It should treat it as local variable and it should work.
If any doubts please comment.
Revision [ Final solution ] - solution for : it works for existing fields when we are adding new fields this is not working.
Problem: With translation mechanism is that it listens the backend.form.extendFieldsBefore event for form and then register fields for translation. When we try to register new fields in form using extendFormFields extension, It happens afterward so new added fields are not visible to translation listener. so they are kind of skipped as translation field registration process already been done.
Solution: So for solution we can just add our field before translation registartion happens. luckily translate plugin has lowest -1 priority for listening this event backend.form.extendFieldsBefore so we can register our fields before It so we are good now and our fields can be added before it can process fields for translation.
Code
\Event::listen('backend.form.extendFieldsBefore', function($widget) {
// You should always check to see if you're extending correct model
if (!$widget->model instanceof \RainLab\User\Models\User) {
return;
}
// we will merge current fields with fields we want to add
// we used shorthand + plus operator for this
$widget->tabs['fields'] = $widget->tabs['fields'] + Config::get('rms.secis::user_fields');
// here Config::get('rms.secis::user_fields') is just returning field array
// Fo ref. Ex:
// return [
// 'gender' => [
// 'label' => 'Gender',
// 'tab' => 'Security Island',
// 'type' => 'radio',
// 'options' => [
// 'male' => 'Male',
// 'female' => 'Female'
// ],
// 'span' => 'auto'
// ],
// ];
});
Note: we are adding fields to tab so we are using $widget->tabs['fields'] to add fields to the tabs. If you want to add normal fields or secondary tab fields you can use $widget->fields and $widget->secondaryTabs['fields] respectively.
Yes now translator can see our fields and its processed, It should able to show translation UI in frontend-ui as well.
if any doubts please comment.

#hardik-satasiya
yes, no more errors on frontend, but new problem is, that no translate functions on fields.
Maybe to add jQuery Script to Controller?
Integration without JQuery and October Framework files:
https://octobercms.com/plugin/rainlab-translate
end of documentation

Related

Create Remote Select2 v4 Option with custom parameters

here is the problem, I can create the custom option as specify on documentation like this:
var option = new Option("my custom option", "myid", true, true);
$('select[name="myselect"]').append(option).trigger('change');
// manually trigger the `select2:select` event
$('select[name="myselect"]').trigger({
type: 'select2:select',
params: {
data: {
id: "myid",
text: "my custom option",
customparam: {
hello: "I'm here"
}
}
}
});
So, this creates the option normally and shows on select2 as selected as expected, this also trigger the select2:select event and I can read the extra parameter when this event is trigger, but here comes the problem, I can NOT access the extra parameter by doing this:
$('select[name="myselect"]').select2('data')[0].customparam
it's like the custom parameter is not attached to the element and it was only pass to the events.
for all who try to find an solution to add the custom parameters back on remote select2, here is what I did and worked perfectly:
$('select[name="yourfieldname"]')
.append(new Option(`${doc.n}`, doc._id, true, true))
.select2('data')[0].customparam = doc.i;
then just when you need call:
$('select[name="yourfieldname"]').select2('data')[0].customparam
The method described by #rafaelrglima's works for me, but I prefer the method below, which was gleaned from dejan9393's answer in Github issue 2830:
var dataAdapter = $('select[name="myselect"]').data('select2').dataAdapter;
dataAdapter.addOptions(dataAdapter.convertToOptions([{
id: "myid",
text: "mycustomoption",
customparam: "hello"
}]));
I prefer this way because I don't have to have one step for adding "id" and "text" and separate step for adding custom parameters. Also convertToOptions takes an array, so you have a convenient way to add multiple options in one step.

antd prepopulate tags and multi select

I'm working on antd select and having issues with prepopulating it correctly, I can prepopulate the select box via its initialValue field decorator, however it populates strings, there does not appear to be a way to have a value (something I can work around but not ideal), and more importantly if the option is unselected/removed, it is no longer available in the select, unlike standard options. I can include in both select list options and initial value (as demonstrated in code below) but then it allows duplicate auto entry and it appears twice in the drop down list. Any ideas what I'm doing wrong?
Preperation of Preselected and Full Option List
let defaultSelect = [];
let selectList = [];
for (var a = 0; a < this.props.myData.length; a++) {
//push all options to select list
selectList.push(<Select.Option key={this.props.myData[i].id} >{this.props.myData[i].name}</Select.Option>)
//this is my code to pre-populate options, by performing a find/match
let matchedTech = _.find(this.props.myDataPrepopulate, { id: this.props.myData[i].id });
if (matchedTech) {
//notice I can push just the string name, not the name and the id value.
defaultSelect.push(this.props.myData[i].name);
}
}
Select Code
{getFieldDecorator(row.name, {
initialValue: defaultSelect
})(
<Select
tags
notFoundContent='none found'
filterOption={(input, option) => option.props.children.toLowerCase().indexOf(input.toLowerCase()) >= 0}
{selectList}
</Select>
)}
I think I understand your question, even if you posted code that doesn't run.
<Select.Option> works just like the plain html <select><option/></select>. In order to give the option a value it needs a value attribute, which is used to identify the option.
See http://codepen.io/JesperWe/pen/YVqBor for a working example.
The crucial part transformed to your example would become:
this.props.myData.forEach( data => {
selectList.push(<Select.Option value={data.id} key={data.id}>{data.name}</Select.Option>);
} );
defaultSelect = this.props.myDataPrepopulate.map( data => data.id );
(I took the liberty to use a bit more modern code patterns than your original)

Right way to attach a jQuery-UI dateselect to a Zend Framework 2 form element?

What would be the right way to attach a jQuery-UI dateselect to a Zend Framework 2 form element?
Would it be adding a appendScript so a javascript selector is added to the end of the layout that selects the class/id?
First of all, i strongly suggest to go with the time and to start using Zend\Form\Element\Date. All browsers who do not support the Date-Input will still render out a Input of type="text", so there is literally no loss in doing so.
The advantage you do get is that most modern browsers are able to render out there default Datepicker. Using the browsers defaults is preferred for users usability and comfort. Even IE10 does do a very good job of supporting the current neat stuff of CSS3 and HTML5. But of course you can't be sure and so you should always include a fallback for older browsers, too. For this, I strongly suggest that you run with Feature-Detection in favor of blindly overwriting the users defaults. The library that does the job the best probably is Modernizr. I will give you the JS for that at the end.
Another thing to note is that this kind of JavaScript belongs at the BOTTOM of your document. For this you have to print this right before closing your </body>-Tag
<?=$this->inlineScript();?>
Now print the script you want inside the right place like this inside your $action.phtml
<?php $this->inlineScript()->captureStart(); ?>
Modernizr.load({
test: Modernizr.inputtypes.date,
nope: [
'http://ajax.googleapis.com/ajax/libs/jquery/1.4.4/jquery.min.js',
'http://ajax.googleapis.com/ajax/libs/jqueryui/1.8.7/jquery-ui.min.js',
'jquery-ui.css'
],
complete: function () {
$('input[type=date]').datepicker({
dateFormat: 'yy-mm-dd'
});
}
});
<?php $this->inlineScript()->captureEnd(); ?>
What's happeing there is that the Modernizr-library will check for the browser support of the Date-Input of HTML5. If the browser is not able to render out a DateSelect, the appropriate JavaScript-Libraries will be loaded (jQuery, jQueryUI and CSS) and attached to the DOM and the jQueryUI.datepicker() will be called to your input-elements of type date.
In addition, all of this JS-Stuff will be captured and moved to the END of your DOM (where a script element will be added). Doing this you have the advantage that first the full DOM will be rendered and then the JS will be attached. Meaning your Form is usable sooner than in the example provided by Raj.
Based on the 2 answers, I did a bit more research and came up with my own approach...
Here is the top of my layout.phtml
$this->inlineScript()->offsetSetFile(10,$basePath . '/jquery/jquery-1.10.1.min.js');
$this->inlineScript()->offsetSetFile(12,$basePath . '/jquery-ui/ui/jquery-ui.min.js');
I have assigned all my javascripts with an ID so they are all loaded in the right order.
I then use this in my Form... by default it looks like any form element has the ID set to its name, this makes ite easy to style with input#name
$this->add(array(
'name' => 'start',
'type' => 'DateTime',
'options' => array(
'label' => 'Start Date',
'format' => 'Y-m-d H:i P',
),
));
Its then very easy to style with the following, here is my $action.phtml ...
echo $this->form($form);
# Decorations
$this->inlineScript()->offsetSetScript(99,"
$(function() {
$('input#start').datepicker({
dateFormat: 'yy-mm-dd',
showOtherMonths: true,
selectOtherMonths: true,
});
});
");
You can see here I have assigned it offset 99. This is what I use in all my templates.

Kendo UI Grid in MVC with Conditional Custom Command Button

I have a KendoUI Grid I'm using an MVC web application, all working fine however I want to add a custom command button that is shown conditionally in the UI and simply executes a command on my controller passing it the required parameter.
columns.Command(command => command.Custom("UnlockAccount").SendDataKeys(true).Click())
The command is specified as above but I only want the button to show when the DataItems IsLocked property is true.
I also cannot figure out how to just call and method on the controller rather. I cannot find a demo of this on the Kendo site and not sure how to move this forward.
Here is a specific example for using client templates for conditional command buttons.
const string ShowUpdateButton = "#if (IsNetReversal == false) {#<a class='k-button k-button-icontext k-grid-edit' href='\\#'><span class='k-icon k-edit'></span>Update</a>#}#";
const string ShowReverseButton = "#if (IsNetReversal == false) {#<a class='k-button k-button-icontext k-grid-reverse' href='/JournalDetail/Reverse/#: ID #' ><span class='k-icon k-reverse'></span>Reverse</a>#}#";
const string ShowDeleteButton = "#if (IsAdjustment == true) {#<a class='k-button k-button-icontext k-grid-delete' href='\\#'><span class='k-icon k-delete'></span>Delete</a>#}#";
You can do the template inline but I find it easier (particularly for multiple buttons) if you declare constants and then use string.format to concatenate them.
col.Template(o => o).ClientTemplate(string.Format("{0}{1}{2}", ShowUpdateButton, ShowDeleteButton, ShowReverseButton));
The upside is it will work with popup editor whereas jquery hacks will ignore the conditional status when a user cancels out of edit. A cancel from the popup editor will restore the grid row from the viewmodel or wherever Kendo stores it which results in button states from before any jquery/javascript hack. The method above will also auto-wire the standard commands since I copied their HTML output for the client template.
The downside is that if Kendo changes their pattern for command buttons the client template may fail. I tired several other methods besides this one and the downside to this method seems better than the other methods.
Note on Kendo Forums: As of the date of this post, they do not appear to allow people who do not pay for support to post to the forums so I would suggest posting questions here instead. They monitor Stack Overflow and in my experience they seem to answer questions more quickly here.
Use template column instead - via the ClientTemplate method.
Conditional templates are covered here and multiple times on the forums - the Command columns is not that flexible.
As of the December 2018 release of Kendo, you can now conditionally display custom buttons more easily, but it still relies on JavaScript to do its work, this function should be defined before your dataGrid or you'll run into issues.
function showCommand(dataItem) {
console.log("determining to hide or show" + dataItem);
// show the Edit button for the item with Status='New'
if (dataItem.Status == 'New') {
return true;
}
else {
return false;
}
}
Then the code for the Grid.
.Columns (columns => {
columns.Command (
command => command.Custom ("Approve")
.Visible ("showCommand")
.Click ("approveFunc")
)
.Width (100)
.HeaderTemplate ("Actions")
})
You can control custom command button visibility by Visible property.
columns.Command(command => command.Custom("UnlockAccount").SendDataKeys(true).Click().Visible("unlockAccountVisible"))
Visible property accepts JS function name and passes current dataItem as an argument.
JS function that evaluates button visibility:
<script>
function unlockAccountVisible(dataItem) {
// show the UnlockAccount button only when data item property IsLocked == true
return dataItem.IsLocked;
}
</script>
Read more in Show Command Buttons Conditionally kendo-ui documentation article.

Grails: How do I make a g:textfield to load some data and display it in other g:textfield?

I have two g:textfields
in the first one I should write a number lets say 12 and in the g:textfield next to it it should load the predetermined name for number 12.
The first one is named 'shipper' and the other 'shipperName'
Whenever I write the code 12 in the 'shipper' txtfield, it should return the name of the shipper in the 'shipperName' box.
Thanks in advance!
Examples:
If I write the number 12 it should return USPS
http://i53.tinypic.com/2i90mc.jpg
And every number should have a different 'shipperName'
Thanks again!
That's quite easy if you'll use jQuery. Check out the event handlers ("blur" is the one you want which occurs when the user leaves the numerical box).
For example:
$("#shipper").blur(function() {
$("#shipperName").load(
"${createLink(controller: 'shipper', action: 'resolveShipper')}?id=" +
$("#shipper").val()
);
});
The $(this).val() at the end is the value of the input field the user just left.
And the "ShipperController.resolveShipper" action would look something like this:
def resolveShipper = {
render text: Shipper.get(params.id).name, contentType: "text/plain"
}
There are other things you might want to do, like automatically filling in the shipperName field as the user types without leaving the edit field, probably after a delay. However the event handler stays the same, just the event is changing (from "blur" to "change" or something like this)
To relate two strings, it's easiest to use an object to create a dictionary/ map, as shown below;
$('#input1').bind('keyup',function() {
var map = {
"1":"One",
"2":"Fish",
"3":"Bar"
};
$('#input2').val(map[$(this).val()]);
});
You can see this in action here: http://www.jsfiddle.net/dCy6f/
If you want the second value only to update when the user has finished typing into the first input field, change "keyup" to "change".

Resources