Suitecrm/Sugarcrm ..How to assign an array in template file? - crm

Here the controller view file SuiteCRM/modules/Contacts/views/view.detail.php
<?php
if(!defined('sugarEntry') || !sugarEntry) die('Not A Valid Entry Point');
require_once('include/MVC/View/views/view.detail.php');
require_once('api/soap_api.php');
class ContactsViewDetail extends ViewDetail
{
/**
* #see SugarView::display()
*
* We are overridding the display method to manipulate the portal information.
* If portal is not enabled then don't show the portal fields.
*/
public function display(){
global $sugar_config;
$aop_portal_enabled = !empty($sugar_config['aop']['enable_portal']) && !empty($sugar_config['aop']['enable_aop']);
//echo '<pre>===='; print_r($aop_portal_enabled); exit;
$this->ss->assign("AOP_PORTAL_ENABLED", $aop_portal_enabled);
require_once('modules/AOS_PDF_Templates/formLetter.php');
formLetter::DVPopupHtml('Contacts');
$admin = new Administration();
$obj = new AirtelUserInfo();
$res = $obj->test();
$sql = 'select * from contacts';
//$result = $this->db->query($sql,true," Error filling in additional detail fields: ");
// Get the id and the name.
//$row = $this->db->fetchByAssoc($result);
//echo '<pre>'; print_r($sql); exit;
$this->ss->assign("res", $res);
$admin->retrieveSettings();
if(isset($admin->settings['portal_on']) && $admin->settings['portal_on']) {
$this->ss->assign("PORTAL_ENABLED", true);
}
parent::display();
}
}
here the tpl file path
SuiteCRM/cache/modules/Contacts/DetailView.tpl
<script language="javascript">
{literal}
SUGAR.util.doWhen(function(){
return $("#contentTable").length == 0;
}, SUGAR.themes.actionMenu);
{/literal}
</script>
<table cellpadding="0" cellspacing="0" border="0" width="100%" id="">
<tr>
<td class="buttons" align="left" NOWRAP width="80%">
<div class="actionsContainer">
<form action="index.php" method="post" name="DetailView" id="formDetailView">
<input type="hidden" name="module" value="{$module}">
<input type="hidden" name="record" value="{$fields.id.value}">
<input type="hidden" name="return_action">
<input type="hidden" name="return_module">
<input type="hidden" name="return_id">
<input type="hidden" name="module_tab">
<input type="hidden" name="isDuplicate" value="false">
<input type="hidden" name="offset" value="{$offset}">
<input type="hidden" name="action" value="EditView">
<input type="hidden" name="sugar_body_only">
</form>
<ul id="detail_header_action_menu" class="clickMenu fancymenu" ><li class="sugar_action_button" >{if $bean->aclAccess("edit")}<input title="{$APP.LBL_EDIT_BUTTON_TITLE}" accessKey="{$APP.LBL_EDIT_BUTTON_KEY}" class="button primary" onclick="var _form = document.getElementById('formDetailView'); _form.return_module.value='Contacts'; _form.return_action.value='DetailView'; _form.return_id.value='{$id}'; _form.action.value='EditView';SUGAR.ajaxUI.submitForm(_form);" type="button" name="Edit" id="edit_button" value="{$APP.LBL_EDIT_BUTTON_LABEL}">{/if} <ul id class="subnav" ><li>{if $bean->aclAccess("edit")}<input title="{$APP.LBL_DUPLICATE_BUTTON_TITLE}" accessKey="{$APP.LBL_DUPLICATE_BUTTON_KEY}" class="button" onclick="var _form = document.getElementById('formDetailView'); _form.return_module.value='Contacts'; _form.return_action.value='DetailView'; _form.isDuplicate.value=true; _form.action.value='EditView'; _form.return_id.value='{$id}';SUGAR.ajaxUI.submitForm(_form);" type="button" name="Duplicate" value="{$APP.LBL_DUPLICATE_BUTTON_LABEL}" id="duplicate_button">{/if} </li><li>{if $bean->aclAccess("delete")}<input title="{$APP.LBL_DELETE_BUTTON_TITLE}" accessKey="{$APP.LBL_DELETE_BUTTON_KEY}" class="button" onclick="var _form = document.getElementById('formDetailView'); _form.return_module.value='Contacts'; _form.return_action.value='ListView'; _form.action.value='Delete'; if(confirm('{$APP.NTC_DELETE_CONFIRMATION}')) SUGAR.ajaxUI.submitForm(_form);" type="submit" name="Delete" value="{$APP.LBL_DELETE_BUTTON_LABEL}" id="delete_button">{/if} </li><li>{if $bean->aclAccess("edit") && $bean->aclAccess("delete")}<input title="{$APP.LBL_DUP_MERGE}" class="button" onclick="var _form = document.getElementById('formDetailView'); _form.return_module.value='Contacts'; _form.return_action.value='DetailView'; _form.return_id.value='{$id}'; _form.action.value='Step1'; _form.module.value='MergeRecords';SUGAR.ajaxUI.submitForm(_form);" type="button" name="Merge" value="{$APP.LBL_DUP_MERGE}" id="merge_duplicate_button">{/if} </li><li><input class="button" id="manage_subscriptions_button" title="{$APP.LBL_MANAGE_SUBSCRIPTIONS}" onclick="var _form = document.getElementById('formDetailView');_form.return_module.value='Contacts'; _form.return_action.value='DetailView'; _form.return_id.value='{$fields.id.value}'; _form.action.value='Subscriptions'; _form.module.value='Campaigns'; _form.module_tab.value='Contacts';_form.submit();" name="Manage Subscriptions" type="button" value="{$APP.LBL_MANAGE_SUBSCRIPTIONS}"/></li><li><input type="button" class="button" onClick="showPopup();" value="{$APP.LBL_GENERATE_LETTER}"/></li><li>{if !$fields.joomla_account_id.value && $AOP_PORTAL_ENABLED}<input title="{$MOD.LBL_CREATE_PORTAL_USER}" class="button" onclick="var _form = document.getElementById('formDetailView');_form.action.value='createPortalUser';_form.submit();" name="buttonCreatePortalUser" id="createPortalUser_button" type="button" value="{$MOD.LBL_CREATE_PORTAL_USER}"/>{/if}</li><li>{if $fields.joomla_account_id.value && !$fields.portal_account_disabled.value && $AOP_PORTAL_ENABLED}<input title="{$MOD.LBL_DISABLE_PORTAL_USER}" class="button" onclick="var _form = document.getElementById('formDetailView');_form.action.value='disablePortalUser';_form.submit();" name="buttonDisablePortalUser" id="disablePortalUser_button" type="button" value="{$MOD.LBL_DISABLE_PORTAL_USER}"/>{/if}</li><li>{if $fields.joomla_account_id.value && $fields.portal_account_disabled.value && $AOP_PORTAL_ENABLED}<input title="{$MOD.LBL_ENABLE_PORTAL_USER}" class="button" onclick="var _form = document.getElementById('formDetailView');_form.action.value='enablePortalUser';_form.submit();" name="buttonENablePortalUser" id="enablePortalUser_button" type="button" value="{$MOD.LBL_ENABLE_PORTAL_USER}"/>{/if}</li><li>{if $bean->aclAccess("detail")}{if !empty($fields.id.value) && $isAuditEnabled}<input id="btn_view_change_log" title="{$APP.LNK_VIEW_CHANGE_LOG}" class="button" onclick='open_popup("Audit", "600", "400", "&record={$fields.id.value}&module_name=Contacts", true, false, {ldelim} "call_back_function":"set_return","form_name":"EditView","field_to_name_array":[] {rdelim} ); return false;' type="button" value="{$APP.LNK_VIEW_CHANGE_LOG}">{/if}{/if}</li></ul></li></ul>
</div>
</td>

In your view you will need to assign your variable in the display method like following:
$myArray = array(1000, 1001, 1002);
$this->ss->assign("myArray", $myArray);
Then you will need to edit the smarty template:
<ul>
{foreach from=$myArray item=foo}
<li>{$foo}</li>
{/foreach}
</ul>

Related

How to pass a js variable to the controller in ASP.NET Core

I am sending an id in my js code and I want to pass that variable to my controller. Any advice on how I can do that?
<input class="btn_confirm" type="submit" id={i}
onclick="id_click(this.id)" value="Delete" />
var id;
function id_click(clicked_id) {
id = clicked_id;
}
I tried different things but nothing worked out.
I tried as below:
Model:
public class ReceiveModel
{
public int Id { get; set; }
public string Name { get; set; }
public string SomeKey { get; set; }
}
View:
<div class="row">
<div class="col-md-4">
<form id="form" asp-action="Create">
<div asp-validation-summary="ModelOnly" class="text-danger"></div>
<div class="form-group">
<label asp-for="Name" class="control-label"></label>
<input asp-for="Name" class="form-control" />
<span asp-validation-for="Name" class="text-danger"></span>
</div>
<div class="form-group">
<input id="1" type="submit" value="Create" class="btn btn-primary" />
</div>
<div class="form-group">
<input id="2" type="submit" value="Create" class="btn btn-primary" />
</div>
<div class="form-group">
<input id="3" type="submit" value="Create" class="btn btn-primary" />
</div>
</form>
</div>
</div>
<script src="~/lib/jquery/dist/jquery.min.js"></script>
<script>
$("input[type='submit']").click(function ()
{
var tempid = this.id
var tmpInput = $("<input type='text' name='SomeKey' hidden/>");
tmpInput.attr("value", tempid );
var form = $("#form")
form.append(tmpInput)
form.submit()
})
</script>
Result:
You can lookup API requests. If you want to send one parameter as a primitive type (string, integer, etc.) you can use query strings in your API calls. For example, let's assume you have an API endpoint like this: localhost:5000/api/YourController. You can send params via API get calls like this localhost:5000/api/YourController?yourParam=<param-value>. In this example your API call type is GET.
If you want to send complex types (like classes, objects) to your controller you can lookup POST API requests.
You can find more details in this documentation.

I try to upload images and input text field to ASP Net Core Web API but controller not read (Angular 13, NET 5)

I need to upload product details and product images into ASP.NET core web API. I implement HTML files as below
<form [formGroup]="myForm" (ngSubmit)="submit()">
<mat-card>
<h2 class="fw-bold text-center">Product Management</h2>
<label class="fw-bold" for="">Product Name</label>
<input type="text" name="name" id="name" formControlName="ProductName" class="form-control">
<input type="text" name="description" id="description" placeholder="Product Description" class="form-control mt-3 mb-2" formControlName="ProductDescription">
<input type="text" name="price" id="price" placeholder="Product Price" class="form-control mt-3 mb-2" formControlName="price">
<input type="text" name="created" id="created" placeholder="Product created" class="form-control mt-3 mb-2" formControlName="created">
<input type="text" name="cat" id="cat" placeholder="Product created" class="form-control mt-3 mb-2" formControlName="ProductCatID">
<input type="file" name="Image" id="Image" class="form-control mt-3 mb-2" (change)="onFileChange($event)" formControlName="ImageUrl">
<img [src]="imageSrc" *ngIf="imageSrc" style="height: 300px; width:500px">
<button type="submit" class="btn btn-primary btn-block mt-3">Submit</button>
</mat-card>
</form>
This is TS file i have implement for the submit data
submit(){
console.log(this.myForm.value);
this.http.post('https://localhost:5001/api/Products', this.myForm.value)
.subscribe(res => {
console.log(res);
alert('Uploaded Successfully.');
})
}
I have implemented Controller As bellow. this controller not read
[HttpPost]
public async Task<ActionResult<ProductDto>> CreateProductAsync(CreateProductDto pro, IFormFile Image)
{
try
{
if (Image == null || Image.Length == 0)
{
return Content("File not selected");
}
var path = Path.Combine(_environment.WebRootPath, "wwwroot//images", Image.FileName);
//Saving the image in that folder
using (FileStream stream = new FileStream(path, FileMode.Create))
{
await Image.CopyToAsync(stream);
stream.Close();
}
pro.ImageUrl = Image.FileName;
var productEntity = _mapper.Map<Product>(pro);
var newProduct = _SqlService.AddProduct(productEntity);
var productForReturn = _mapper.Map<ProductDto>(newProduct);
return CreatedAtRoute("GetProduct", new { id = productForReturn.ProId },
productForReturn);
}
catch(Exception ex)
{
return StatusCode(500, $"Internal server error: {ex}");
}
}
Folder Structure
I need to upload images into the web API folder and as well as I need store the image and product details in SQL Database

Why does my onClick() button call the HttpPost method within my controller?

I have a button which onClick() execute a JS script, but for some reason it keeps executing my SubmitForm() Action method within my controller and i don't understand why
#using (Html.BeginForm("SubmitForm", "Home", FormMethod.Post,
new
{
traName = Request.Form["nameOfTra"],
amount = Request.Form["amountRequested"],
memberName = Request.Form["commiteeMember"],
date = Request.Form["agmDate"],
signed = Request.Form["signed"],
dated = Request.Form["dated"],
numberOfRows = Request.Form["numberOfRows"]
}))
{
<h1 style="text-align: center;"> TRA grant application </h1>
<h4 style="text-align: center;">This is the TRA Grant form for the association named below who agree to use these funds to cover the cost of administration of the TRA</h4>
<p>
<label for="nameOfTralbl">Name of TRA:</label>
<input type="text" name="nameOfTra" value="" />
</p>
<h4> List of items the money will be spent on</h4>
<table id="traTable">
<tr>
<td>Description of Items</td>
<td>Quantity</td>
<td>Cost</td>
</tr>
<tr>
<td><input type='text' size="30" /></td>
<td><input type='text' size="30" /></td>
<td><input type='text' size="30" /></td>
</tr>
</table>
<br />
<button onclick="addRow()">Add Item</button>
<input type="hidden" id="rows" value="1" name="numberOfRows" />
<script>
function addRow() {
var table = document.getElementById("traTable");
var row = table.insertRow(-1);
var cell1 = row.insertCell(0);
var cell2 = row.insertCell(1);
var cell3 = row.insertCell(2);
cell1.innerHTML = "<input type='text' size='30' id='cell1_" + $('#rows').val() + "'/>";
cell2.innerHTML = "<input type='text' size='30' id='cell2_" + $('#rows').val() + "'/>";
cell3.innerHTML = "<input type='text' size='30' id='cell3_" + $('#rows').val() + "'/>";
$('#rows').val(parseInt($('#rows').val()) + 1)
}
</script>
public ActionResult SubmitForm(string traName, float? amount,
string memberName, string date, string signed, string dated, int? numberOfRows, HttpPostedFileBase file, HttpPostedFileBase file2, HttpPostedFileBase file3){}
I have some extra logic in my Submitform() action which I dont want to execute, I dont understand why it keeps calling this action which it should simply just call the script.
You not declared your submit button to your SubmitForm(). Add inside FormBegin your submit button:
<input type="submit" value="Submit Button" />
#Edit:
Change:
<button onclick="addRow()">Add Item</button>
To:
<input type="button" onclick="addRow()" value="Add Item"/>

spring+ thymeleaf unable to update

Hi I am working with spring MVC and thymeleaf and I am not able to update data from my controller as I have following code.The main problem I am facing is that my put method is not getting called.
#GetMapping("/{id}/edit")
public String editUser(#PathVariable("id") int id, Model model) {
logger.info("++++++++++++[edit User]\n\n" + userService.findById(id));
model.addAttribute("user", userService.findById(id));
return "user/edit";
}
#PutMapping("/{id}/edit")
public String updateUser(#PathVariable("id") int id, #ModelAttribute("user") User user, Model model) {
logger.info("\n\n+++++++++++++++++inside Update");
User toUpdate = userService.findById(user.getId());
user.setUserName(user.getUserName() != null ? user.getUserName() : toUpdate.getUserName());
user.setName(user.getName() != null ? user.getName() : toUpdate.getName());
logger.info(user.toString());
userService.updateUser(user);
model.addAttribute("user", userService.findById(user.getId()));
return "redirect:/user/" + id;
}
and my html page
<form action="#" th:action="#{/user/__${user.id}__}" method="put"
th:object="${user}">
<div class="form-group">
<label for="txtUserName">User-name</label> <input
class="form-control" id="txtUserName" placeholder="User Name"
th:feild="${user.userName}" />
</div>
<div class="form-group">
<label for="txtName">First Name</label> <input
class="form-control" id="txtName" placeholder="Full Name"
th:feild="${user.name}" />
</div>
<div class="form-group">
<label for="calDob">Date of Birth</label> <input
class="form-control" id="calDob" placeholder="dd/MM/yyyy" />
</div>
<button type="submit" th:method="put" class="btn btn-success">Update</button>
<a href="#" th:href="#{/user/__${user.id}__}"
class="btn btn-primary">Cancel</a> <a th:method="delete"
href="javascript:deleteUser('${user.id}');" class="btn btn-danger">Delete</a>
</form>
any help will be usefull thanks
PUT is not a valid argument for method attibute of the form tag. See HTML specification.
Valid methods are GET and POST. And as it's not a REST API, you can use POST method to update.
So just update your mapping from:
#PutMapping("/{id}/edit")
to
#PostMapping("/{id}/edit")
And form tag to:
<form action="#" th:action="#{/user/__${user.id}__}/edit" method="post" th:object="${user}">

Conditionally disable validation

I have form with few text boxes which goes through validation (both server and client sides). In the form I have buttons: "Next", "Back", "CanceL". So I don't need validation to fireup then user clicks "back" or "cancel" buttons. How can I achieve this?
Thanks in advance!
Some sample:
<div class="buttons">
<input type="submit" name="cancelButton" value="" />
<input type="submit" name="backButton" value="" />
<input type="submit" name="nextButton" value="" />
</div>
<% using (Html.BeginForm()) { %>
<p>
<table style="width: 200px">
<tr><td align="center" colspan=2><%= Html.ValidationMessageFor(m => m.street) %><%= Html.DropDownListFor(m => m.street, Model.streetsList) %></td></tr>
<tr><td colspan=2> </td></tr>
<tr><td valign="bottom" align="right" style="width: 75px"><%= Html.LabelFor(m => m.flatNumber) %>:</td><td align=left><%= Html.TextBoxFor(m => m.flatNumber, new { maxlength = 6, style = "width: 48px;" })%> <%= Html.ValidationMessageFor(m => m.flatNumber) %></td></tr>
</table>
<br />
<input type="submit" class="refusal button red floatL" name="cancelButton" value="" />
<input type="submit" class="back button green floatL" name="backButton" value="" />
<input type="submit" class="continue button green floatR marR" name="nextButton" value="" />
</div>
<div class="clear">
</div>
<% } %>
At the server side I use DataAnnotations attributes for validation.
the Button class has a CausesValidation property - if that is set to false, validation won't be triggered on postback.
Example:
<asp:Button id="btnCancel" CausesValidation="false" onClick="bntCancel_Click" Text="Cancel" runat="server" />
Note that this will disable the ASP.NET validators - if you have your own validation you will need to disable it another way.
Surround the text boxes with a form and turn next, back, and cancel into submit buttons. On event onsubmit, assign a method which returns true if the form is valid and should proceed to send it to the server, otherwise false.
So I would expect something along the lines of:
<form id="navigatorForm">
<!-- Various text forms here -->
<input type="submit" value="Back" onsubmit="back()" />
<input type="submit" value="Next" onsubmit="next()" />
<input type="submit" value="Cancel" onsubmit="cancel()" />
<input type="hidden" id="operation" name="operation" value="" />
</form>
<script type="text/javascript">
function validate() {
// Perform validation here
// If okay, return true, else false
}
function next() {
document.getElementById('operation').value = 'next';
if(!validate()) {
alert('Form is not filed correctly. Please pay more attention!');
return false; // Do not send to server!
} else {
return true;
}
}
function back() {
document.getElementById('operation').value = 'back';
return true;
}
function cancel() {
document.getElementById('operation').value = 'cancel';
return true;
}
</script>
Notice that unlike next(), back() and cancel() unconditionally return true, meaning that the request is sent to the server in any circumstance. At this point, on the server side, you'd need only to check to see if operation is next to know whether or not you should perform further testing.

Resources