We can easily embed a controller within a template in twig:
{% render "AcmeGolferBundle:Golfer:showGolfersList" %}
When we basically use a controller like this:
/**
* Lists all golfers.
*
* #Route("/golfersList", name="golfers_list")
* #Template()
*/
public function showGolfersListAction()
{
//....doStuff
}
In that case, the only use of the controller will be in that template. Is there a way to avoid the user to trigger the url directly, meaning /golferList on its own?
EDIT
The point I am trying to make is the following:
I need the user to use the controller through the template it is embedded in, but not directly via the url. I realise this might not be possible, but because the controller is embedded, it doesn't have a proper css structure. Therefore, if it is triggered via the url directly, it will look pretty ugly on the page.
Securing route by IP might be useful for you:
security:
# ...
access_control:
- { path: ^/golferList, roles: IS_AUTHENTICATED_ANONYMOUSLY, ip: 127.0.0.1 }
Related
I'm new to Drupal and have been asked to add a redirect in a custom module that was written for us. Unfortunately, the redirect is not working.
The module is implemented as a Block and is working without the redirect code. The module has a Form at the docroot\modules\custom\modulename\src\Form\filename.php location which is what I'm trying to edit.
This Form has a submitForm function in it in which I'm trying to use the following code:
$response = new RedirectResponse('/');
$response->send();
return;
This block has been placed on a page. Let's call it "/en/testpage". However, despite trying all sorts of valid pages in the RedirectResponse such as '/', '/en/members', etc., after the form is submitted, the user is always taken back to https://theNameOfTheWebsite/en/testpage#block-theNameOfTheBlock instead of what I'm trying to redirect to.
I would greatly appreciate if anyone would know how I could resolve this. I have been stuck on this problem for the last 2 days. Thanks. If it helps, the folder structure within the module's folder is similar to the following: "src\Form", "Plugin\Block", "template".
Hi mkha13 Welcome to Stackoverflow
your code is not working with your redirection code
Check your log messages first if there is any logged message about this
at
/admin/reports/dblog
Check if you are not including RedirectResponse class
If not included, include this with this line at top of your form class
use Symfony\Component\HttpFoundation\RedirectResponse;
Another solution is
/**
* {#inheritdoc}
*/
public function submitForm(array &$form, FormStateInterface $form_state) {
$form_state->setRedirect("routingName");
}
routingName is the machine name mentioned in the routing file.
Redirect to front page
$form_state->setRedirect('<front>');
Hope this helps you
many times I see, for example in Symfony:
html file:
<hr>
<?php $this->generateUrl('blog_show', array('slug' => 'slug-value')); ?>
<br>
this is a bad smell, like not using depencency injection: this way HTML is coupled to the current framework. I have to edit it if I want to move it to another framework.
Wouldnt it be better to just pass the generated url string from the controller?
You can separate your view from your backend as you want, but your frontend file has to refer to an url at some point, even if it is just an api.
Changing your url from <?php $this->generateUrl('blog_show', array('slug' => 'slug-value')); ?> to <?php $showUrl; ?> just make it less maintainable and harder to migrate to another framework.
If you want to be Framework Independant you should use Symfony backend like an API.
The url could be generated in the controller to separate model from view. But it's only a first step. The best way is to separate model, view and routing. I think the best way is to use a view helper which generates the path. I changed some framework for project (abandonware to symfony). It is easier when the project used a template (like Smarty or Twig)
Take a look at Symfony Twig extensions to have some example which separates path generation and controller.
As example, Twig purpose the path method. This view helper is searching the url path from the route paramter. It doesn't have any relation with controller or model.
path : Returns the relative URL (without the scheme and host) for the given
route. If relative is enabled, it'll create a path relative to the
current path.
As you can see there you only have to be carefull to the route name.
/**YourController**/
/**
* #Route("/foo", name="new-game", methods="get")
*
* #return Response
*/
public function myFooAction()
{
//Your code
//The rendering without information about his own or other path
return $this->render('default/foo.html.twig', []);
}
And the corresponding path in Twig :
<hr>
Some text
<br>
I am having a weird situation which has halted my progress for the second day now and I am almost going bald from pulling my hair on this. I have a custom block on the sonata admin dashboard which is not being found when I try to load the page.
I have gone over the configuration a couple of times and maybe I am missing something which an extra pair of eyes may be able to spot which is why I am posting this question here.
I have built my block as below and saved it under src\AppBundle\Block\NumbersBlockService.php
namespace AppBundle\Block;
use Symfony\Component\HttpFoundation\Response;
use Sonata\AdminBundle\Form\FormMapper;
use Sonata\AdminBundle\Validator\ErrorElement;
use Sonata\BlockBundle\Model\BlockInterface;
use Sonata\BlockBundle\Block\BaseBlockService;
use Sonata\BlockBundle\Block\BlockContextInterface;
use Doctrine\ORM\Query\ResultSetMapping;
use Symfony\Component\OptionsResolver\OptionsResolverInterface;
use DoctrineExtensions\Query\Mysql;
class NumbersBlockService extends BaseBlockService
{
......
}
Then defined my service in the service.yml file as below:
sonata.block.service.topnumbers:
class: AppBundle\Block\NumbersBlockService
arguments:
- sonata.block.service.topnumbers
- "#templating"
- "#doctrine.orm.entity_manager"
- "#security.token_storage"
tags:
- { name: sonata.block }
My config.yml file includes the block like this
sonata_block:
default_contexts: [cms]
blocks:
sonata.user.block.menu: # used to display the menu in profile pages
sonata.user.block.account: # used to display menu option (login option)
sonata.block.service.text: # used to if you plan to use Sonata user routes
sonata.block.service.topnumbers:
and finally, I position the block on top with the line below
sonata_admin:
dashboard:
blocks:
- { position: top, type: sonata.block.service.topnumbers, class: col-md-12}
I have checked the tutorial on creating a custom block here https://sonata-project.org/bundles/block/master/doc/reference/your_first_block.html and everything seems to check out but I still get the following error below:
An exception has been thrown during the rendering of a template ("The block type "sonata.block.service.topnumbers" does not exist") in SonataAdminBundle:Core:dashboard.html.twig at line 60.
Someone please help put me out of my misery. Thanks in advance
I'm building a web application using symfony2. I have different types of users with different roles; ROLE_STUDENT and ROLE_TEACHER, those two user can access a course's details; if the user is a teacher, a button edit is shown and if it's the student then a button subscribe will be shown, and actually this is not secure because it just hides the path to the controllers action, if the student types in the address bar /course/2/edit the edit action would be executed so I had to secure the action using #security annotation:
This is what I have done so far:
/**
* #Security("has_role('ROLE_TEACHER')")
*/ public function editAction()
{}
and in twig :
{% if is_granted('ROLE_TEACHER') %}
edit
{% elseif is_granted('ROLE_STUDENT')%}
subscribe
.
The problem is that I have a lot of accessible content to both users and I think there is a better solution to this instead of copy/past the same code all over. I'm new to Symfony 2, please bear with me.
There are multiple ways to achieve this but what you are doing is not wrong.
One way to achieve this is to set ROLE for the ROUTES so that ROLE_STUDENT roles can only access URLs that will be something like this website.com/students and ROLE_TEACHER can only access website.com/teachers
access_control:
- { path: ^/student/, roles: ROLE_STUDENT }
- { path: ^/teamleader/, roles: ROLE_TEACHER }
You can then set the edit route only for teachers like website.com/teachers/course/2/edit this way no edit route is going to be available for ROLE_STUDENT and they will get 404 error or access denied error if they try to access teacher route. You can do the same for the subscribe feature.
Like I said there are more ways to achieve this and this is one of them.
I'm currently toying around with making a framework-only SilverStripe site and so far so good - I've set up a controller and some models and all is well there, however I'm having issue with creating a login system.
It seems the $Form variable that normally displays the login form when you visit /admin doesn't display anything. Should it? I thought that it would, however it is not doing.
I guess my question is - do framework only sites use the default login form, and if so what are the first steps to troubleshoot why the form is not showing on my site? Could it have something to do with routes?
Here is my code:
Routes.yml
---
Name: app
After: 'framework/routes'
---
Director:
rules:
'': 'GanttController'
'$URLSegment//$Action/$ID/$OtherID': 'GanttController'
GanttController.php
<?php
class GanttController extends BaseController {
public function index() {
return $this->customise(new ArrayData(array(
'Title' => 'Gantt Chart'
)))->renderWith(array(
'GanttController',
'Page'
));
}
Page.ss
<html>
<head>
<title>$Title</title>
</head>
<body>
<div class="header">
<h1>Gantt</h1>
</div>
<div class="pane">
$Layout
$Form
</div>
</body>
</html>
If I add the line 'admin': 'AdminRootController' to my YAML routes and go to /admin, instead of it loading up my project it loads up the get started with the SilverStripe framework page, where it links you to the docs on adding controllers/templates.
the framework should display the $Form given that you have a template that uses it.
the framework is still designed to have a frontend, this means to 2 things:
framework will use templates/Page.ss as default template for frontend as usual
if you want the admin / or the secuirty login form, you need to access this controller
you can do this 3 ways:
access it via the already existing route: /admin or /Security/login?backURL=/the/url/to/redirect/to/after/login
use a http redirect make / redirect to /admin
if you don't want a frontend at all, you just use Page.ss for the login template and make / to show the same thing as /admin by assiging the route / to the AdminRootController with the following yml config:
File: mysite/_config/routes.yml
---
Name: mysiteroutes
Before: '*'
After:
- '#rootroutes'
- '#coreroutes'
- '#modelascontrollerroutes'
- '#adminroutes'
---
Director:
rules:
'': 'AdminRootController'
if this does not answer your question and you still can't get the form to display, please paste your code (your route configs, your Page.ss, and any relevant Controller you might have).