Laravel user forms and admin forms: how to tackle? - forms

Just a question to poll how you guys would tackle this in Laravel:
I have a user preferences page defined in UserController.php which creates the view at user/preferences.blade.php.
Administrators should of course be able to edit the user's preferences and have some extra administrative fields shown to be changed. Furthermore I'd like to collect all admin functionality concerning users in a separate controller called AdminUserController.php
I'm thinking of some possibilities to achieve this functionality:
Create an additional view (e.g. admin/user/preferences.blade.php) and almost replicate the GET and POST methods of UserController.php to accommodate the extra fields. However this seems to me like a lot of redundant code...
Convert the GET and POST methods of UserController.php to something like this:
public function postPreferences($user = NULL, $admin = FALSE) {
if (!isset($user)) $user = Auth::user();
// Process regular fields.
if ($admin) {
// Process admin fields.
}
}
Add the admin fields to user/preference.blade.php and conditionally show them if $admin is TRUE, and then call the UserController's methods from within AdminUserController, e.g.:
public function postPreferences($user) {
return (new UserController)->postPreferences($user, TRUE);
}
However, there are some drawbacks. First: controllers shouldn't call each other... Second: this only works for the POST method. Upon requesting the GET method from UserController an exception is being thrown...
I'm curious about how you would tackle this!
Thanks.

This is mostly a question of preference, but I really suggest you to completely separate all that is possible here. Administration is a process that is very sensitive and not in any way should it be possible, that a normal user will be able to see it under any circumstance.
I believe that we all are humans and we make mistakes more or less often, that's why we need to make sure that our mistakes in not assigning right value to the right variable or making a type of = instead of == not to ruin business logic.
I think you should make a separate view and a separate controller for user self management and administration and never tie them up. If you want to keep your code DRY as much as possible, you may extend your user controller and model from your admin controller and model, but not the other way around. That's just my 2 cents, it all depends on what type of application you are working on and what the stakes are.
<?php
class AdminController extends UserController
{
public function __construct(AdminModel $model)
{
// Use dependency injection
$this->model = $model;
}
// In the original UserController class:
public function postPreferences($user) {
$this->model->edit($user, Input::all());
// you may do it this way so your user only saves user data and
// you admin model saves all the data including administrative
}
// ...
}

Related

Shopware 6 Forms

Newbie question. How to handle Storefront Form Submit in Shopware 6? How to save the data from form to database? I have an entity, form shown in storefront and a controller but i have no idea how to save the data to entity. Thanks in advance.
you would have to be more specific with the description, of what exactly you are trying to achieve.
But in general, if you already have a controller, that receives the data, then you can get them from the request like this:
$data = $request->request->all();
By this, you have all the values from your form saved in an array $data. You have written, that you already have an entity, so from that I assume, that your entity is already mapped to your database table. So the only thing you have to do, is to use the repository to save the data. For thta, you just need to inject it into your class and get a context. The context depends on where you currently are, so for the purpose of the example, I have just created the default context.
It should look like this:
class MyClass
{
protected $myEntityRepository;
public function __construct(
MyEntityRepository $myEntityRepository
)
{
$this->myEntityRepository = $myEntityRepository;
$this->context = \Shopware\Core\Framework\Context::createDefaultContext();
}
public function myMethod ($data)
{
$this->myEntityRepository->upsert($data, $this->context);
}
}
Hope this helps. I have actually written an article on repositories in Shopware 6, so if you want to get some more information and examples, you can check it here: https://shopwarian.com/repositories-in-shopware-6/.

Apache Isis: How to implement your custom submit form or page properly?

I'm new at Apache Isis and I'm stuck.
I want to create my own submit form with editable parameters for search some entities and a grid with search results below.
Firstly, I created #DomainObject(nature=Nature.VIEW_MODEL) with search results collection, parameters for search and #Action for search.
After deeper research, I found out strict implementations for actions (For exapmle ActionParametersFormPanel). Can I use #Action and edit #DomainObject properties(my search parameters for action) without prompts?
Can I implement it by layout.xml?
Then I tried to change a component as described here: 6.2 Replacing page elements, but I was confused which ComponentType and IModel should I use, maybe ComponentType.PARAMETERS and ActionModel or implement my own IModel for my case.
Should I implement my own Wicket page for search and register it by PageClassList interface, as described here: 6.3 Custom pages
As I understood I need to replace page class for one of PageType, but which one should I change?
So, the question is how to implement such issues properly? Which way should I choose?
Thank you!
===================== UPDATE ===================
I've implemented HomePageViewModel in this way:
#DomainObject(
nature = Nature.VIEW_MODEL,
objectType = "homepage.HomePageViewModel"
)
#Setter #Getter
public class HomePageViewModel {
private String id;
private String type;
public TranslatableString title() {
return TranslatableString.tr("My custom search");
}
public List<SimpleObject> getObjects() {
return simpleObjectRepository.listAll();
}
#Action
public HomePageViewModel search(
#ParameterLayout(named = "Id")
String id,
#ParameterLayout(named = "Type")
String type
){
setId(id);
setType(type);
// finding objects by entered parameters is not implemented yet
return this;
}
#javax.inject.Inject
SimpleObjectRepository simpleObjectRepository;
}
And it works in this way:
I want to implement a built-in-ViewModel action with parameters without any dialog windows, smth like this:
1) Is it possible to create smth like ActionParametersFormPanel based on ComponentType.PARAMETERS and ActionModel and use this component as #Action in my ViewModel?
2) Or I should use, as you said, ComponentType.COLLECTION_CONTENTS? As I inderstand my search result grid and my search input panel will be like ONE my stub component?
Thank you.
We have a JIRA ticket in our JIRA to implement a filterable/searchable component, but it hasn't yet made it to the top of the list for implementation.
As an alternative, you could have a view model that provides the parameters you want to filter on as properties, with a table underneath. (I see you asked another question here on SO re properties on view models, so perhaps you are moving in that direction also... I've answered that question).
If you do want to have a stab at implementing that ticket, then the ComponentTYpe to use is COLLECTION_CONTENTS. If you take a look at the isisaddons, eg for excel or gmap3 then it might help get you started.
======= UPDATE TO ANSWER (based on update made to query) ==========
I have some good news for you. v1.15.0-SNAPSHOT, which should be released in the couple of weeks, has support for "inline prompts". You should find these give a user experience very similar to what you are after, with no further work needed on your part.
To try it out, check out the current trunk, and then load the simpleapp (in examples/application/simpleapp). You should see that editing properties and invoking actions uses the new inline prompt style.
HTH
Dan

How to customize register and contact forms in PrestaShop?

I need to know how to customize my contact and register forms. How to add new fileds ( and ) and make the information from these fields required or not required.
I need to know which files I must edit for these forms...
I use prestashop 1.4.7.0
This is really two separate questions as there are major differences in how you would handle each case.
Answer 1
For the registration form you can write a module which contains two hook handler functions. These will be:
public function hookCreateAccountForm() {}
public function hookCreateAccount($params) {}
The first function allows you to add additional fields to the registration form (by default these are inserted at the end of the form authentication.tpl, although you could move them all as a single group elsewhere). It should simply return the additional form html you require.
The second function provides you with two parameters to handle the account creation process. This is executed after the standard fields have been validated and the new customer has been created. Unfortunately you cannot do validation on your additional fields using this (you would need to either use javascript or override AuthController to perform your own authentication in the preProcess() member function). In one of my own custom modules for a site I have the following, for example:
public function hookCreateAccount($params)
{
$id_lang = (int)Configuration::get('PS_LANG_DEFAULT');
$customer = $params['newCustomer'];
$address = new Address(Address::getFirstCustomerAddressId((int)$customer->id));
$membership_number = $params['_POST']['membership_number'];
....
....
}
$params['newCustomer'] is a standard Prestashop element in the array and contains the newly created customer object. Your fields will be in the $params['_POST'] array - in my case it was an input field called membership_number.
Answer 2
For the contact form it's a whole lot more complicated I'm afraid. The simplest method for the html is to just hard-code your additional fields in the template file contact-form.tpl.
To actually process the form you will need to create an override for the controller by ceating a file called ContactController.php in /<web-root>/<your-optional-ps-folder>/override/controller containing something like:
<?php
class ContactController extends ContactControllerCore {
function preProcess()
{
if (Tools::isSubmit('submitMessage'))
{
// The form has been submitted so your field validation code goes in here.
// Get the entered values for your fields using Tools::getValue('<field-name>')
// Flag errors by adding a message to $this->errors e.g.
$this->errors[] = Tools::displayError('I haven't even bothered to check!');
}
parent::preProcess();
if (Tools::isSubmit('submitMessage') && is_empty($this->errors))
{
// Success so now perform any addition required actions
// Note that the only indication of success is that $this->errors is empty
}
}
}
Another method would be to just copy the entire preProcess function from controllers\ContactController and just hack away at it until it does what you want....

authorization on wicket component using wicket auth-role

I am using wicket 1.4.9 and implemented spring + wicket auth-role and using #AuthorizeInstantiation based on roles on pages. I have multiple custom roles.
I have followed this link to implement the basics:
https://cwiki.apache.org/WICKET/spring-security-and-wicket-auth-roles.html
After that I have implemented my own UserDetailsService to have my own roles/users from database.
Now, How can I impose controls on roles with components eg, Links,Buttons ? like
link A can be accessed only by SUPER_USER, DR_MANAGER. (roles comes from database).
I have done like this and it seems to work, but is that the good way to do this? OrbitWebSession is of type AuthenticatedWebSession.
#Override
public boolean isVisible() {
if(OrbitWebSession.get().getRoles().hasRole("SUPER_USER")){
return true;
}
return false;
}
thanks.
Overriding isVisible all the time is a major pain. Take a look at MetaDataRoleAuthorizationStrategy instead. You call authorize(Component component, Action action, String roles) with Action RENDER, and the roles you want to allow. This way the component, whatever it is, is automatically hidden for other roles provided that the authorization strategy is registered in your webapplication. Basically it does the same thing as Holms answer, except you don't have to subclass anything.
You are in the right track, the only change I would do is:
#Override
public boolean isVisible() {
return super.isVisible() && OrbitWebSession.get().getRoles().hasRole("SUPER_USER");
}
That way you don't accidentally override its default visible behavior for example if the parent component is not visible.
Using the #AuthorizeAction annotation you can control wether the component is rendered or not based on roles. It's quite easy to use, but you have to subclass the component that you want to authorize.
#AuthorizeAction(action = Action.RENDER, roles = { "SUPER_USER", "DR_MANAGER" })
class UserAdminPageLink extends BookmarkablePageLink<String> {
//Implementation…
}
add(new UserAdminPageLink("UserAdminPageLink", UserAdminPage.class));
Check out Wicket Examples - Authorization for some working code.

Zend_Acl modular class system

Hey guys, I'm starting with Zend, and trying to understand the way it works (getting there), and with Acl classes, people seem to declare all the roles and resources in one file. Now to me this seems a bit of a waste of system resources if the person is only logging in as a basic user, or even just a guest/visitor to the site. So I was thinking is it possible to have different classes which set the roles dependant on the role/resource of the current user.
My current idea is to use switch/case on the role in the bootstrap, and load individual Acl classes based on the role name (for example sake, 'visitor' => 'Model_VisitorAcl', 'users' => 'Model_UserAcl' and 'admin' => 'Model_AdminAcl'), each with a corresponding class file. Then within the class files do something for each one. This is working, and currently I could define all my 'admin' acls in one (backtracking through the rights heirarchy of admin-user-visitor), then in 'user' have 'user'-'visitor' roles and resources.
However this doesn't seem the best way, as if I wanted to change the role permissions for 'user' I'd need to change it for 'user' and 'admin'. This is obv not a problem with 2 roles, but on bigger systems it obviously is.
So I tried something like
class Model_AdminAcl extends Zend_Acl{
function __construct(){
$d = new Model_UserAcl();
//defining the admin role and permissions, with inheritance from the roles
//set in Model_UserAcl
}
}
To try and get the Model_UserAcl construct function to run, thus setting the role 'user', however this does not seem to work, throwing "Uncaught exception 'Zend_Acl_Role_Registry_Exception' with message 'Parent Role id 'users' does not exist'"
error.
So whats the next step? Having individual include files for each module, and have the required classes include them as needed?
Or am I just making mountain out of molehills with this issue?
Thanks,
Psy
Ok, solved this, not sure why I didn't think to try this in the first place (Friday brain frazzle I think)
I just put the contents of the constructor into its own function, and then called that function in the constructor, and make the classes inherit from the class below it.
//Model/VisitorAcl.php
class Model_VisitorAcl extends Zend_Acl{
function __construct(){
$this->addVisitorRules();
}
function addVisitorRules(){
//adding the role and permissions
}
}
//Model/UserAcl.php
class Model_UserAcl extends Model_VisitorAcl{
function __construct(){
$this->addVisitorRules();
$this->addUserRules();
}
function addUserRules(){
//adding the role and permissions
}
}
//Model/AdminAcl.php
class Model_AdminAcl extends Model_AdminAcl{
function __construct(){
$this->addVisitorRules();
$this->addUserRules();
$this->addAdminRules();
}
function addAdminRules(){
//adding the role and permissions
}
}
If this is not the way I should go about it, then by all means please let me know.
Psy