How to change default template in Yii2? - yii2

I am using the Yii 2 Advanced Application Template, the AdminLTE Asset Bundle and the Gii code generator.
Here is my example:
I need to change the template so I can remove the "Create Lab Tipos Movimientos" button (and modify some things more).
I am removing every button after Gii create the CRUD but I would like to change the template so Gii can do it automatically.

Once you have create your own template for gii
You can change the default template for gii assigning the new template values in main.php (main-local.php)
assigning the proper parameter to gii module
.....
$config['modules']['gii'] = [
//'class' => 'yii\gii\Module',
'class' => 'your_gii_module_path\Module',
'allowedIPs' => ['127.0.0.1', '::1', ],
'generators' => [ //here
'crud' => [ // generator name
//'class' => 'yii\gii\generators\crud\Generator', // generator class
'class' => 'your_gii_module_path\generators\crud\Generator', // generator class
'templates' => [ //setting for out templates
// template name => path to template
'your_crud_entry' => 'your_absolute_path_\your_gii_module_path\generators\crud\default',
]
]
],
];
.......

I have not done it myself, but I found this Guide by SamDark in Github that explains how to create your own template. This is the url: https://github.com/yiisoft/yii2-gii/blob/master/docs/guide/topics-creating-your-own-templates.md
Additionally, if you just want to eliminate the "Create Lab Tipos Movimiento" button you can try modifying the current template which if I am not wrong is located inside the folder vendor/yiisoft/yii2-gii/generators/crud/default/views and the file should be index.php. There you can try deleting or better yet commenting the part of the code that says:
<p>
<?= "<?= " ?>Html::a(<?= $generator->generateString('Create ' . Inflector::camel2words(StringHelper::basename($generator->modelClass))) ?>, ['create'], ['class' => 'btn btn-success']) ?>
</p>
I suggest you to make a copy of the files you modify just in case anything goes wrong.
Hope this helps you.
Have a great day.
EDIT:
Additionally following the answer of schmunk to a very similar question in stack overflow found here: How to use custom templates in gii (using Yii 2)
There is apparently a Gii extension in beta phase to help you in this situation called yii2-giiant found here: https://github.com/schmunk42/yii2-giiant (maybe there are similar extensions that are in a more advanced phase of development, google search should help with that)

Related

How to correctly specify migration namespace classes in yii2?

could someone explain me how can I correctly specify my modules migration namespaces? As I see in the documentation, it's:
return [
'controllerMap' => [
'migrate' => [
'class' => 'yii\console\controllers\MigrateController',
'migrationNamespaces' => [
'app\migrations', // Common migrations for the whole application
'module\migrations', // Migrations for the specific project's module
'some\extension\migrations', // Migrations for the specific extension
],
],
],
];
But there are no explanation in which file should I write the commands. I've tried it in config.php, as:
'controllerMap' => [
'migrate' => [
'class' => 'yii\console\controllers\MigrateController',
'migrationNamespaces' => [
'app\modules\adBoard\migrations',
],
But I don't know which controller class should I write. Could someone tell me in which file I have to specify it and how to specify it correctly?
If you refer to this documentation
Configuring Command Globally
Instead of entering the same option
values every time you run the migration command, you may configure it
once for all in the application configuration like shown below:
return [
'controllerMap' => [
'migrate' => [
'class' => 'yii\console\controllers\MigrateController',
'migrationTable' => 'backend_migration',
],
], ];
With the above configuration, each time you run the migration command, the backend_migration table will be used to record
the migration history. You no longer need to specify it via the
migrationTable command-line option.
Namespaced Migrations
Since 2.0.10 you can use namespaces for the
migration classes. You can specify the list of the migration
namespaces via migrationNamespaces. Using of the namespaces for
migration classes allows you usage of the several source locations for
the migrations. For example:
return [
'controllerMap' => [
'migrate' => [
'class' => 'yii\console\controllers\MigrateController',
'migrationNamespaces' => [
'app\migrations', // Common migrations for the whole application
'module\migrations', // Migrations for the specific project's module
'some\extension\migrations', // Migrations for the specific extension
],
],
], ];
this config should be placed in you console/config/main.php
but for namespaced migration remeber that starting for 2.0.10
depending on your yii2-template application (basic or advanced) the location of "console" specific settings are located in different directories.
For basic template, console fetch settings from <app>/config/console.php file.
And for advanced template, you should edit <app>/console/config/main.php file.
Remember that your settings for console will not affect web-settings, so if you want to register some component in the whole project, you have to duplicate it in both files.
P.S. I would like to add one more detail about advanced template, is that it has common setting for frontend and backend sub-apps, which is located in <app>/common/config/main.php, but those settings are not common with console commands.
I would like to share my experience with Yii2 namespaced migrations.
Scenario
I am using advanced template.
I have 100s of old migrations in console/migrations folder.
I have new extension which have namespaced migrations.
I have new migrations in old folder console/migrations.
I want to create future migrations with namespaces in new folder console/migrations/namespaced. I want to keep all old migrations intact which are located at console/migrations.
console/config/main.php configurations worked for me.
return [
'controllerMap' => [
'migrate' => [
'class' => \yii\console\controllers\MigrateController::class,
'migrationNamespaces' => [
'console\migrations\namespaced',
'yii\swiftsmser\migrations'
]
],
],
//.... more configurations
];
With above configurations, when I executed yii migrate, It includes all above mentioned folders.
Note: To create new migration. Just make sure to use command like below.
yii migrate/create console\\migrations\\namespaced\\DLTTemplatesForSMS

Yii2 render database content

There is a textarea where user can edit some templates and can use variables like:
{{model.user.name}}
Application need to replace this variables with data and display HTML output.
We can write a small function that will replace variables from template with data but we need to use a template engine like Twig or Smarty.
https://github.com/yiisoft/yii2-twig
https://github.com/yiisoft/yii2-smarty
Now we can use ViewRenderer from Smarty or Twig.
$render = new ViewRenderer();
$content = $render->render($this->view,'template.twig',[
'model' => $model,
]);
But I see this error:
Unable to find template "template.twig" (looked into: .).
How can I use Smarty or Twig to render a template with the content from database in Yii2 ?
I found Mustache ( https://github.com/bobthecow/mustache.php ) and I'm using like this:
$m = new \Mustache_Engine();
echo $m->render("Hello {{model.client.firma}}",['model' => $model]);
You don't create a renderer manually, you configure your application components, like this:
[
'components' => [
'view' => [
'class' => 'yii\web\View',
'renderers' => [
'twig' => [
'class' => 'yii\twig\ViewRenderer',
'cachePath' => '#runtime/Twig/cache',
// Array of twig options:
'options' => [
'auto_reload' => true,
],
'globals' => ['html' => '\yii\helpers\Html'],
'uses' => ['yii\bootstrap'],
],
// ...
],
],
],
]
You are telling Yii that there is a renderer to handle templates with the .twig extension.
Then, all you need to do is add the .twigextension when calling render in your controller actions:
public function actionIndex()
{
return $this->render('index.twig');
Then put your twig templates in the view folders where the views normally go.
Read the documentation for the twig extension: Twig Extension for Yii 2
If you want to only use twig templates, you can avoid specifying the extension (.twig) if you set the default extension:
'components' => [
'view' => [
'defaultExtension' => 'twig',
You should create a twig component which will wrap around Twig_Environment. You can add yii\twig\Extension extension if you need. Then you should use it like this:
$renderedTemplate = Yii::$app->twig->render($template, $context);
If you really need to render a template from a string variable you may implement your own Twig_LoaderInterface. There is a Twig_Loader_String, but it's deprecated and you should not use it.

Leaflet extension and Geosearch Directory not found

Im relatively new to the Yii framework. I'm trying to get leaflet extension to work on my project. I installed it via composer and everything seems to be installed properly but when I try to insert it into an activeForm it throws me this error:
The file or directory to be published does not exist: /vendor/bower/leaflet/dist
Im trying to build a Geosearch field with a map.
The extensions I have installed are:
"2amigos/yii2-leaflet-extension": "~1.0",
"2amigos/yii2-leaflet-geocoder-plugin": "~1.0",
"2amigos/yii2-leaflet-geosearch-plugin": "~1.0"
This is my code on the ActiveForm (its just the same as the provided on GitHub):
use dosamigos\leaflet\layers\TileLayer;
use dosamigos\leaflet\LeafLet;
use dosamigos\leaflet\types\LatLng;
use dosamigos\leaflet\plugins\geosearch\GeoSearch;
use dosamigos\leaflet\widgets\Map;
<?php
$center = new LatLng(['lat' => 39.67442740076734, 'lng' => 2.9347229003906246]);
$geoSearchPlugin = new GeoSearch([
'service' => GeoSearch::SERVICE_OPENSTREETMAP
]);
$tileLayer = new TileLayer([
'urlTemplate' => 'link not allowed because its one of my first posts...',
'clientOptions' => [
'attribution' => 'Tiles Courtesy of MapQuest ' . ', ' . 'Map data © OpenStreetMap contributors, ' . 'CC-BY-SA', 'subdomains' => '1234'
]
]);
$leafLet = new LeafLet([
'name' => 'geoMap',
'tileLayer' => $tileLayer,
'center' => $center,
'zoom' => 10,
'clientEvents' => [ // setting up one of the geo search events for fun
'geosearch_showlocation' => 'function(e){ console.log(e.target); }'
]
]);
// add the plugin
$leafLet->installPlugin($geoSearchPlugin);
// run the widget (you can also use Map::widget([...]))
echo $leafLet->widget();
?>
Is there something I'm missing or doing wrong?
Thanks in advanced
Your problem is that the original Leaflet js and css files are no longer available through Bower, and 2amigos have not changed their composer file to reflect the changes. Yii is attempting to publish a css file from the requested location, and the file doesn't yet exist, hence the error message. You'll either need to go to the original Leaflet repository and copy the relevant files into the required directories, or update the composer file to point to the original files on GitHub. Sorry, I don't know enough about composer to be able to help with this bit!

How I can to turn off a theme in a especific yii2's view?

I am using yii2 with a bootstrap's theme, the theme is great but I need to turn off in one especific view of my controller. How I can do that?
You can change the theme at runtime by overriding the theme mapping. Adjust these for the routes you want to use, so if you are using a different theme, then point the pathMap and baseUrl to that theme, otherwise just point back to the original yii2 view files;
$this->getView()->theme = Yii::createObject([
'class' => '\yii\base\Theme',
'pathMap' => ['#app/views' => '#app/views'],
'baseUrl' => '#web/views',
]);
If you want change layout use in controller:
public $layout = 'YOUR_LAYOUT_NAME';
Or in special action:
public function actionView(){
$this->layout = 'YOUR_LAYOUT_NAME';
Read for $layout property http://www.yiiframework.com/doc-2.0/yii-base-controller.html#$layout-detail

An easy way to load ACL in Zend Framework 2?

I have been following this guide to load my menu configuration and i think it is very nice and clean way to load the menu.
My question is simple, is there a way to load your ACL configuration on the same way with a config array and some kinda of factory?
If there isn't, how do i load a ACL configuration and use with that menu in a easy way?
Thanks!
Edit:
This is a very good blog post on why use modules that is already done and not make your own, http://hounddog.github.com/blog/there-is-a-module-for-that/
ZF2 contains ACL and also RBAC (role based ACL - might be in ZF2.1), but to put it in place, easier is to use module which you can plug into your application. BjyAuthorize seems to me a bit bloated, you have to use ZfcUser module. I prefer ZfcRbac, the ACL rules are based on user roles (group) and their access to controller, action or route. Configuration stored in one config file, really easy to implement.
Most likely there are several ways to do it, but I prefer to do it in getViewHelperConfig() of application's Module.php (here I use BjyAuthorize module to simplify work with ACL, and in particular it allows to set ACL rules in configuration file module.bjyauthorize.global.php)
public function getViewHelperConfig()
{
return array(
'factories' => array(
'navigation' => function($sm) {
$auth = $sm->getServiceLocator()->get('BjyAuthorize\Service\Authorize');
$role = $auth->getIdentityProvider()->getIdentityRoles();
if (is_array($role))
$role = $role[0];
$navigation = $sm->get('Zend\View\Helper\Navigation');
$navigation->setAcl($auth->getAcl())->setRole($role);
return $navigation;
}
)
);
}
Play with This structure . get role and resource from database and save this in session for or any caching .
You are right, there is no out-of-the-box-all-in-one solution. You have to build some bridges between the modules.
Another easy way to integrate BjyAuthorize is using **Zend Navigation**s default methods as described by Rob Allen:
Integrating BjyAuthorize with ZendNavigation
$sm = $e->getApplication()->getServiceManager();
// Add ACL information to the Navigation view helper
$authorize = $sm->get('BjyAuthorizeServiceAuthorize');
$acl = $authorize->getAcl();
$role = $authorize->getIdentity();
ZendViewHelperNavigation::setDefaultAcl($acl);
ZendViewHelperNavigation::setDefaultRole($role);
You can also use ZfcRbac and use a listener to make it work with Zend Navigation.
Since this is a lot of code I simply post the link here:
Check Zend Navigation page permissions with ZfcRbac – Webdevilopers Blog
I've just created an ACL module that creates an ACL Service parsing the routes.
To manage your access control to your application you only need to define roles and add a new key 'roles' in every route. If you do not define that key or its array is empty, then the route becomes public. It also works with child routes.
As an example:
array(
'router' => array(
'routes' => array(
'user\users\view' => array(
'type' => 'Segment',
'options' => array(
'route' => '/admin/users/view/id/:id/',
'constraints' => array(
'id' => '[0-9]+',
),
'defaults' => array(
'controller' => 'User\Controller\Users',
'action' => 'view',
'roles' => ['admin', 'user'],
),
),
),
),
),
);
The module can be installed via composer and it is now listed in the zend modules repository: http://zfmodules.com/itrascastro/TrascastroACL
You can get more detailed info about use and installation from my blog: http://www.ismaeltrascastro.com/acl-module-zend-framework/