Best practice to add a Test-Button in a Orchard-AdminView - orchardcms

I'd like to add a "Test"-Button to the Create/Edit-AdminViews in my Orchard-Module.
The Button itself is rendered fine using an additional shape.
Question: how can I make the button's action point to a "Test"-Action which gets the current ViewModel, performs the "Test", displays an info and returns the user to the view (passing the ViewModel back in again).
At the Moment, it completely ignores it's surrounding Form.
Maybe there's already some working example and I simply couldn't find it?
Thanks for any help.
Sascha
PS: Code in Content.TestButton.cshtml
#using ( Html.BeginFormAntiForgeryPost(Url.Action("Test", new { controller = "DnsCheckAdmin" }), FormMethod.Post, new { #class = "col-md-5" }) )
{
<fieldset class="test-button">
<button type="submit" name="submit.Test" value="submit.Test">#T("Test settings")</button>
</fieldset>
}

Related

Update #Html.Partial() View only

I am not looking for a javascript/jquery answer. I can do that, but I feel like it breaks the purpose. This seems like something that should be possible without javascript.
I'm trying to get a simple listbox selection to update an #Html.Partial section, and I'm not exactly sure what to do. Everything loads initially just fine. After I submit, however, I am not quite sure how to 'attach' to my partial view to update it.
The purpose here is to only load the listbox one time, and let them view or request as many new reports as they want without reloading. If it's not possible, that's fine, I can use one page, reload the listboxes, and it will work. I just don't see why I would need to go to the database to reload the listbox items every time they view or request a report.
"master" html page:
#using TCTReports.Models
#model ReportViewModel
<h2>My Reports</h2>
<div class="row">
<div class="col-md-6">
<h3>Select Report</h3>
#using (Html.BeginForm("GetReport", "Report"))
{
#Html.DropDownListFor(m => m.SelectedMyID, Model.myLB)
<input type="submit" value="View" />
}
</div>
<div class="col-md-6">
<h3>All Reports</h3>
#using (Html.BeginForm("ReqReport", "Report"))
{
#Html.DropDownListFor(m => m.SelectedAllID, Model.allLB)
<input type="submit" value="View" />
}
</div>
</div>
#Html.Partial("_Msg")
_Msg is super simple atm. It would eventually be a report viewer, for now, it looks at #Viewbag...
<h2>#ViewBag.Message</h2>
Controller submit actions (I get my selected value just fine. currently on void but was ActionResult with Views - but I don't feel like that is correct either, as it completely overwrites the page (even with PartialView) and I lose my listboxes and _layout...):
public void GetReport(ReportViewModel model)
{
var myID = model.SelectedMyID;
ViewBag.Message = "Report: " + myID.ToString() + " Selected.";
//return PartialView("_Msg","Test");
}
public void ReqReport(ReportViewModel model)
{
var allID = model.SelectedAllID;
ViewBag.Message = "Report: " + allID.ToString() + " Requested.";
//return PartialView("_Msg", "Test");
}
Ok, so how would I go about updating _Msg and refreshing only the #Html.PartialView() section of my master html page? I played with #sections briefly but didn't make much progress.

update customer attribute in frontend account profile form

I'm learning Shopware and I got to something I can't figure out how to solve.
I'm writing a test plugin that adds an attribute to the customer. I've added the correspondent field to the Registration form and it saves its value to the db automatically, like I read somewhere in the docs.
Now I wanted to let the attribute be editable in the account profile page, after the password field. I managed to put the input there, and even show the value from the db. But when I change the value and save, the value its not updated. I don't know if it is just a matter of getting the field name right, or do I need to override something else. Or is it just not possible? Any help on how to achieve this would be greatly appreciated.
Relevant code below:
plugin bootstrap
public function install(InstallContext $context)
{
$service = $this->container->get('shopware_attribute.crud_service');
$service->update('s_user_attributes', 'test_field', 'string');
$metaDataCache = Shopware()->Models()->getConfiguration()->getMetadataCacheImpl();
$metaDataCache->deleteAll();
Shopware()->Models()->generateAttributeModels(['s_user_attributes']);
return true;
}
register/personal_fieldset.tpl
{extends file="parent:frontend/register/personal_fieldset.tpl"}
{block name='frontend_register_personal_fieldset_password_description'}
{$smarty.block.parent}
<div class="register--test-field">
<input autocomplete="section-personal test-field"
name="register[personal][attribute][testField]"
type="text"
placeholder="Test Field"
id="testfield"
value="{$form_data.attribute.testField|escape}"
class="register--field{if $errorFlags.testField} has--error{/if}"
/>
</div>
{/block}
account/profile.tpl
{extends file="parent:frontend/account/profile.tpl"}
{block name='frontend_account_profile_profile_required_info'}
<div class="profile--test-field">
<input autocomplete="section-personal test-field"
name="profile[attribute][testfield]"
type="text"
placeholder="Test Field"
id="testfield"
value="{$sUserData.additional.user.test_field|escape}"
class="profile--field{if $errorFlags.testField} has--error{/if}"
/>
</div>
{$smarty.block.parent}
{/block}
The form type that it's used on registration isn't the same you have on profile.
If you check \Shopware\Bundle\AccountBundle\Form\Account\PersonalFormType::buildForm, you can see
$builder->add('attribute', AttributeFormType::class, [
'data_class' => CustomerAttribute::class
]);
That means the attributes are included on form and they will be persisted. That's why you can save the value on registration form.
On profile you have \Shopware\Bundle\AccountBundle\Form\Account\ProfileUpdateFormType. And here the attribute isn't added to form builder.
How to extend the ProfileUpdateFormType?
Subscribe Shopware_Form_Builder on Bootstrap (or on a specific Subscriber class)
$this->subscribeEvent('Shopware_Form_Builder', 'onFormBuild');
Create the method onFormBuild to add your logic
public function onFormBuild(\Enlight_Event_EventArgs $event) {
if ($event->getReference() !== \Shopware\Bundle\AccountBundle\Form\Account\ProfileUpdateFormType::class) {
return;
}
$builder = $event->getBuilder();
$builder->add('attribute', AttributeFormType::class, [
'data_class' => CustomerAttribute::class
]);
}
With this approach all attributes are available on your profile form.
Other possibility you have is using the 'additional' property instead of 'attribute' and then subscribe a controller event or hook a controller action to handle your custom data.

Submit Html form with a specific model

I am using MVC, Razor, Knockout, typescript in my application. Need to prepare a excel file with a model/dataset that is set at client side. I am using the following code but the problem i understand is that the dataset is being taken as string and not exactly like the model it is supposed to take as. Here is the code
This is observable (dataset)
vmExportData = ko.observableArray<ExcelModel>([]);
Push data to the dataset
vmExportData.push(new ExcelModel (
e.sender.data()[i].Id,
e.sender.data()[i].Name,
e.sender.data()[i].Address1,
));
Html code, to prepare excel file (at the controller)
#using (Html.BeginForm("ExportToExcel", "MyController", FormMethod.Post, new { enctype = "multipart/form-data" }))
{
<div data-bind="css:{hidden: true}">
<input type="text" data-bind="value: vmExportData" />
</div>
<input class='excelIcon' type="submit" data-ux-access="true" value="">
}
Controller method :
public ActionResult ExportToExcel(ExportModel exportModel)
{
The problem is, the exportModel parameter value is coming as null ! Any other way out to get it to work ? Is there a way to make excel at client side and render as well ?
Try setting name="exportModel" on your tag.
Also make sure to have an [HttpPost] on top of your controller action, since your form method is post.
What does the ExportModel class look like?

Grails search mechanism

I have the folowing gsp page:
<g:form controller="??" action="??">
<h1>Search</h1>
<g:submitButton name="search" value="Search"/>
<div id="resultsHere">
</div>
</g:form>
What i want to do is, everytime "Search is clicked", the database is searched for that record, lets imagine im looking for book titles. So everytime i write a title, the database finds the books and print every data related to the books. How can i do that=?
My idea is having something similar to this in the div:
<ul>
<g:each in="${bookList}">
<li>Name: ${it.name}, Locale: ${it.isbn}</li>
</g:each>
</ul>
So the point is, when the search button is clicked, the controller that handle that action should redirect the page to the same page, and pass the filtered list of books so it can be printed in the <g:each in="${bookList}"> tag.
I would like opinions about this being the best solution in this case. I could also render the results in the page directly, but i would like to do some css for the lookings so i think that wont be a good idea using render. Any help would be apreciated, and if possible, some lights with the code (specially the filtering part).
I would have one action in your controller, and render out the list.
ie: as pseudo-code (and not complete)
BookController {
def search = {SearchComamnd search ->
def books = []
if(search) {
books = Book.createCritera().list {
and {
title(search.title)
author(search.title)
}
}
}
render [ books:books ]
}
class SearchCommand {
def author
def title
}
}
and then when in your view
<g:form controller="??" action="??">
<h1>Search</h1>
<g:submitButton name="search" value="Search"/>
</g:form>
<g:each in="${books}">
<li class="book">Name: ${it.name}, Locale: ${it.isbn}</li>
</g:each>
you can now use css li.book to decorate the entry.

Drupal - Search box not working - custom theme template

I am using a customised version of search-theme-form.tpl
When I use the search box, I do get transferred to the search page. But the search does not actually take place. The search box on the search results page does work though. This is my search-them-form.tpl.php file (demo :
<input type="text" name="search_theme_form_keys" id="edit-search-theme-form-keys" value="Search" title="Enter the terms you wish to search for" class="logininput" height="24px" onblur="restoreSearch(this)" onfocus="clearInput(this)" />
<input type="submit" name="op" id="edit-submit" value="" class="form-submit" style="display: none;" />
<input type="hidden" name="form_token" id="edit-search-theme-form-form-token" value="<?php print drupal_get_token('search_theme_form'); ?>" />
<input type="hidden" name="form_id" id="edit-search-theme-form" value="search_theme_form" />
There is also a javascript file involved. I guess it's use is pretty clear from the code:
function trim(str) {
return str.replace(/^\s+|\s+$/g, '');
}
function clearInput(e) {
e.value=""; // clear default text when clicked
e.className="longininput_onfocus"; //change class
}
function restoreSearch(e) {
if (trim(e.value) == '') {
{
e.value="Search"; // reset default text onBlur
e.className="logininput"; //reset class
}
}
}
What can be the problem and how can I fix it?
Apparently, you cannot directly modify the HTML in search-theme-form.tpl.php since thats not the right way to do it. So my adding the class and onFocus and onBlur attributes was the problem.
The correct way to do it is to modify the themes template.php file. Basically we will be using form_alter() to modify the form elements. Since using the HTML way is wrong. Take a look at the code below (taken from : here )
<?php
/**
* Override or insert PHPTemplate variables into the search_theme_form template.
*
* #param $vars
* A sequential array of variables to pass to the theme template.
* #param $hook
* The name of the theme function being called (not used in this case.)
*/
function yourthemename_preprocess_search_theme_form(&$vars, $hook) {
// Note that in order to theme a search block you should rename this function
// to yourthemename_preprocess_search_block_form and use
// 'search_block_form' instead of 'search_theme_form' in the customizations
// bellow.
// Modify elements of the search form
$vars['form']['search_theme_form']['#title'] = t('');
// Set a default value for the search box
$vars['form']['search_theme_form']['#value'] = t('Search this Site');
// Add a custom class and placeholder text to the search box
$vars['form']['search_theme_form']['#attributes'] = array('class' => 'NormalTextBox txtSearch',
'onfocus' => "if (this.value == 'Search this Site') {this.value = '';}",
'onblur' => "if (this.value == '') {this.value = 'Search this Site';}");
// Change the text on the submit button
//$vars['form']['submit']['#value'] = t('Go');
// Rebuild the rendered version (search form only, rest remains unchanged)
unset($vars['form']['search_theme_form']['#printed']);
$vars['search']['search_theme_form'] = drupal_render($vars['form']['search_theme_form']);
$vars['form']['submit']['#type'] = 'image_button';
$vars['form']['submit']['#src'] = path_to_theme() . '/images/search.jpg';
// Rebuild the rendered version (submit button, rest remains unchanged)
unset($vars['form']['submit']['#printed']);
$vars['search']['submit'] = drupal_render($vars['form']['submit']);
// Collect all form elements to make it easier to print the whole form.
$vars['search_form'] = implode($vars['search']);
}
?>
In yourthemename_preprocess_search_theme_form - 'yourthemename' will obviously reflect the name of your custom theme. Basically the code is self-explanatory. what with the comments and all.
So, basically thats the way it works.

Resources