Perl, Mojolicious, Helper, call method - helper

I see in Mojolicious::Plugin::Yancy helper declaration:
$app->helper( 'yancy.get' => \&_helper_get );
and after that they call helper like
$c->yancy->get( $schema, $id );
But when i try
$app->helper( 'foo.bar' => \&foo_bar_func );
and
$c->foo->bar();
i have error: can't call method "bar" without a package or object referace.
When i try:
$app->helper( 'foobar' => \&foo_bar_func );
and
$c->foo_bar();
...all is ok.
But how does it work in Yancy with "->" ?

Please see https://mojolicious.org/perldoc/Mojolicious/Guides/Cookbook#Adding-a-plugin-to-your-application
Helpers with a dot in them belong to a particular plugin. Are you registering yours within plugin 'foo'?

Related

Error: Call to undefined method CodeIgniter\Database\Postgre\Connection::select()

public function getLoad() {
$q = $this->conn->select('load.level_id, load.section_id, sub.subject_title, sub.subject_name')
->from('academics.tbl_teaching_load load')
->join('academics.tbl_subjects sub', 'sub.subject_id = load.subject_id')
->where('user_id', $this->request->getVar('user_id'))
->get()->getResult();
echo json_encode($q);
}
As the title said, it returns an error: Call to undefined method CodeIgniter\Database\Postgre\Connection::select()
I am new too CI4 and trying to join a table. The only problem I encounter so far is this. I can't seem to find the solution for the problem. Any help or tips will do. TYIA
Error:
Call to undefined method CodeIgniter\\Database\\Postgre\\Connection::select()
Explanation:
The error above is pretty clear. You're trying to call the select(...) method which doesn't exist in the CodeIgniter\Database\Postgre\Connection class.
However, the select(...) method exists in the CodeIgniter\Database\BaseBuilder class. You can receive the BaseBuilder instance from the Connection instance through the inherited CodeIgniter\Database\BaseConnection::table(...) method.
In addition, I would recommend you to first join your table(s) before selecting columns using the ->select(...) method. That would be easier to read and interpret.
Hence, reorder and change your query to...
Solution:
public function getLoad()
{
$q = $this->conn->table('academics.tbl_teaching_load load')
->join('academics.tbl_subjects sub', 'sub.subject_id = load.subject_id')
->where('user_id', $this->request->getVar('user_id'))
->select(['load.level_id', 'load.section_id', 'sub.subject_title', 'sub.subject_name'])
->get()->getResult();
echo json_encode($q);
}

Jest error with <Trans>: You forgot to export your component from the file it's defined in, or you might have mixed up default and named imports

Error: Uncaught [Error: Element type is invalid: expected a string
(for built-in components) or a class/function (for composite
components) but got: undefined. You likely forgot to export your
component from the file it's defined in, or you might have mixed up
default and named imports.
This is the error I was getting while running test in jest. React component which is being tested uses <Trans> from react-i18next. When I comment that portion of code, test were working as expected.
The error shown is very very very miss leading.
In my case it was missing mock for <Trans>. While I had mock for react-i18next, but since I had many components to cover with tests, and some of them were using <Trans> and some of them not, I copy/paste test files but totally forgot to check about mock. It took me few hours to notice it, after I replaced <Trans> to text like <Typography> from material-ui...
jest.mock('react-i18next', () => ({
withTranslation: () => (Component: any) => {
Component.defaultProps = {...Component.defaultProps, t: (children: any) => children};
return Component;
},
Trans: ({children}: any) => children, // this line was missing (() => jest.fn() might also work)
}));
Hope it will save some time for some of you :)
I faced the same issue, in order to resolve the issue I mocked the Trans component like this
jest.mock("react-i18next", () => ({
Trans: ({ i18nKey }: { i18nKey: string }) => i18nKey,
}));
Instead of passing the node, we can simply pass the i18nKey.
In my case, I am only checking the key value. Hope it helps!

Using string.Split() in AutoMapper issue

I have an ASP .Net core application. I am simply trying to have my AutoMapper configure to convert a string comma delimited into a list of strings as per this configuration:
configuration.CreateMap<Job, JobDto>()
.ForMember(dto => dto.Keywords, options => options.MapFrom(entity => entity.Keywords.Split(',').ToList()))
For some reason it does not get compiled and give me the following error:
An expression tree may not contain a call or invocation that uses
optional argument
I can't see why I am getting this error. I am pretty sure that I have done that in my other projects before without any such error.
As error says, Split function has an optional parameter. The full signature of it is as this (options is optional)
public string[] Split(string separator, StringSplitOptions options = StringSplitOptions.None)
As you are trying to use a function with default value inside an expression tree, it gives you the error.
To Fix it, easy, just pass on optional parameters by yourself. ( StringSplitOptions.None )
So, simply change it to this:
entity.Keywords.Split(',' , StringSplitOptions.None).ToList()
This is completely true.
Error is raised because expression tree being created is about to contain some more complex logic, like .Split(',').ToList(), which is not an accessible property or method, only top-level reflected object properties and methods are supported (like in class MemberInfo).
Property chaining, deep-calls (.obj1property.obj2property), extension methods are not supported by the expression trees, like in this .ToList() call.
My solution was like this:
// Execute a custom function to the source and/or destination types after member mapping
configuration.CreateMap<Job, JobDto>()
.AfterMap((dto,jobDto)=>jobDto.Keywords = dto.Keywords.Split(',').ToList());
I had the same problem. I do not know if it is an issue or not. Anyway, I found a workaround.
CreateMap<Category, GetCategoryRest>()
.ForMember(dest => dest.Words,
opt => opt.MapFrom(src => ToWordsList(src.Words)));
private static List<string> ToWordsList(string words)
{
return string.IsNullOrWhiteSpace(words) ? new List<string>() : words.Split(",").ToList();
}
It is guaranteed that AutoMapper has always a List. Still, I'm confused. In my Startup.cs I define that AutoMapper allows null values for list.
Mapper.Initialize(cfg => {
cfg.AllowNullCollections = true;
}
Category.Words is a string.
GetCategoryRest.Words is a List<string>
AutoMapper Version: 8.1.1,
AutoMapper.Microsoft.DependencyInjection: 6.1.1
Use .AfterMap
CreateMap<src, dto>()
.ForMember(src =>src.Categories,options=> options.Ignore())
.AfterMap((src, dto) => { dto.Categories.AddRange(src.Categories.Split(",").ToList()); })
.ReverseMap()
.ForMember(src => src.Categories, option => option.MapFrom(dto => string.Join(",", dto.Categories)));

RequireJS not loading a file or module named "module.js"

I just started using RequireJS. I tried a simple code but one way works but the other doesn't.
folder "script" has "main.js", "module.js", "require.js"
<script data-main="script/main.js" src="script/require.js"></script>
in main.js
requirejs( ['module'], function( mod ) {
mod.sayHello();
} );
in module.js:
define( {
name : "value",
sayHello : function() {
alert( "Hello" );
},
sayBye : function() {
alert( "Bye" );
}
} );
I expect baseUrl to be "script" as mentioned in here:
http://requirejs.org/docs/api.html#jsfiles
The baseUrl is normally set to the same directory as the script used in a data-main attribute for the top level script to load for a page.
So, I thought there would be no problem, but doesn't mod.sayHello() nor sayBye() and console.log( mod.name ) = undefined.
I tried console.log( mod ) and it prints something like this:
Object {id: "_#r6", uri: "script/_#r6.js", exports: Object}
When I use ["script/module.js"] instead of ["module"], console.log( mod ) prints like the following:
Object {name: "value"}
name: "value"
sayBye: ()
sayHello: ()
__proto__: Object
and mod.sayHello(), mod.sayBye(), mod.name all works.
including the following in the beginning of main.js is the same:
requirejs.config( {
baseUrl: "script"
} );
What am I doing wrong... Please help.
Use a different name than module for your module. For one thing, it is a terribly uninformative name, but the module named module is a special module for RequireJS. It is a module that gives information about the module you are currently in. For instance if foo.js contains this code:
define(['module'], function (module) {
console.log(module.id);
});
and this file is loaded when you request the module named foo, then console.log will show "foo" on the console.
The documentation does not highlight the existence of module but it talks about it when explaining what the configuration option config does. Because you get to access the config of your module through module.config().
The reason requiring "script/module.js" works is because when you do this you require a module named script/module.js rather than module.
I continued reading the documentation:
http://requirejs.org/docs/api.html
and it led to a github that has information about this:
https://github.com/jrburke/requirejs/wiki/Differences-between-the-simplified-CommonJS-wrapper-and-standard-AMD-define#magic
It turns out that "module" is a kind of "magic modules" along as "require", "export".
And "module" ... :
gives you information about the module ID and location of the current module
https://github.com/jrburke/requirejs/wiki/Differences-between-the-simplified-CommonJS-wrapper-and-standard-AMD-define#module

Drupal EntityForm hooks

I am using drupal Entity-Form module, I have successfully achieved the user interface part of it. But when i am trying to hook the Entity-form submission, I am not able to get any thing..
I have tried hook_form_alter(), hook_form_FORM_ID_alter(), but nothing.
Has any one achieved it...? I have tried all below:-
function form_submit_igs_entity_views_field_handlers_alter(array &$field_handlers){
echo "pankaj";
}
function _form_entityform_settings_alter(&$form, &$form_state, $form_id) {
echo "pankaj";
}
function form_submit_igs_entity_presave($entity, $type){
echo "pankaj";
}
function form_submit_igs_node_view_alter(&$build){
echo "pankaj";
}
function form_submit_igs_field_attach_submit($entity_type, $entity, $form, &$form_state){
echo "pankaj";
}
function form_submit_igs_form_alter(&$form, &$form_state, $form_id){
echo "pankaj";
}
Here's how I figured it out:
I wrote a hook_form_alter() function it looked like this
function hook_form_alter()(&$form, &$form_state, $form_id) {
dpm($form);
}
from that I could get a formID on the existing form & then get the appropriate name for the function.
Note you can also do:
function hook_form_entityform_edit_form_alter(&$form, &$form_state, $form_id) {
dpm($form);
}
To alter only entity forms.
in both instances hook is to be replaced by your module name. Install devel module to get dpm() function to work and not throw an error.
Hope this helps you figure out your issue.
Not sure what you want to archive, your description is not very good, but anyway.
To alter any entityform form you need to use, as by entityform_forms(), $machine_name . '_entityform_edit_form' as form ID, so your function will look like this some_func_form_YOUR_ENTITY_FORM_NAME_entityform_edit_form_alter().
I have used hook_form_FORM_ID_alter(), you must use your particular entityform's machine name plus _entityform after the machine name. For example if your entityform's machine name is "myentityform" and your module name is "mymodule", the hook_form_FORM_ID_alter will be:
/**
* Implements hook_form_FORM_ID_alter().
*/
function mymodule_form_myentityform_entityform_edit_form_alter(&$form, &$form_state, $form_id)
{
// Your codes
}

Resources