How to represent Attributes with Anonymous Alphabets in view blade in Laravel - laravel

I have this code in Laravel-5.8:
public function index()
{
$userCompany = Auth::user()->company_id;
$departments = HrDepartment::where('company_id', $userCompany)->get();
return view('hr.departments.index')->with('departments', $departments);
}
view
#foreach($departments as $key => $department)
<tr>
<td>
{{$key+1}}
</td>
<td>
{{$department->dept_name ?? '' }}
</td>
<td>
{{isset($department->dept_code) ? $department->dept_code : 'N/A'}}
</td>
</tr>
#endforeach
I don't want the user to see the real department name ( {{$department->dept_name ?? '' }}), but to make it anonymous.
That is, it can randomize {{$department->dept_name ?? '' }} and represent each with alphabets. The first one can be A, second B, C, .... Z
How do I achieve this?
Thanks

You can use this simple function using the ID of the department
function toAlphabet($integer){
$alphabet = array('A','B','C','D','E','F','G','H','I','J','K','L','M','N','O','P','Q','R','S','T','U','V','W','X','Y','Z');
$alpha_flip = array_flip($alphabet);
if($integer <= 25){
return $alphabet[$integer];
}
elseif($integer > 25){
$dividend = ($integer + 1);
$alpha = '';
$modulo;
while ($dividend > 0){
$modulo = ($dividend - 1) % 26;
$alpha = $alphabet[$modulo] . $alpha;
$dividend = floor((($dividend - $modulo) / 26));
}
return $alpha;
}
}
you can then do
toAlphabet($department->id);
//26 will give "AA"
//25 will give "Z"
//19682 will give "ACCA"

Related

Why enter laravel loop data max 40 row?

I created a store function on my controller. At the time I will enter data with just one submit, only indexed up to 40 data will be entered. While those 40 and above do not enter the database. Why did this happen? What's the solution? Please i need help.
Sorry for my bad English.
Thanks
I am use Laravel 5.6
public function store(Request $request)
{
//
foreach($request->quantity as $quantity){
if($quantity == NULL){
}
if($quantity != NULL){
$data = new KomponenOlahan;
$data->quantity = $quantity;
$harga_satuan_mu = Input::get('harga_satuan_mu');
$total = $quantity*$harga_satuan_mu;
$data->kode_proyek = Input::get('kode_proyek');
$data->nama_proyek = Input::get('nama_proyek');
$data->kode_panel = Input::get('kode_panel');
$data->nama_panel = Input::get('nama_panel');
$data->schedule_kirim = Input::get('schedule_kirim');
$data->nama_sales = Input::get('nama_sales');
$data->ukuran_panel = Input::get('ukuran_panel');
$data->ref = Input::get('ref');
$data->type = Input::get('type');
$data->komponen_bantu = Input::get('komponen_bantu');
$data->nama_komponen = Input::get('nama_komponen');
$data->spek = Input::get('spek');
$data->satuan = Input::get('satuan');
$data->diskon = Input::get('diskon');
$data->harga = Input::get('harga');
$data->pole = Input::get('pole');
$data->ka = Input::get('ka');
$data->ampere = Input::get('ampere');
$data->quantity = $quantity;
$data->harga_satuan_mu = $harga_satuan_mu;
$data->harga_satuan_mb = Input::get('harga_satuan_mb');
$data->harga_satuan_lb_oh = Input::get('harga_satuan_lb_oh');
$data->id_estimasi = Input::get('id_estimasi');
$data->nama_estimasi = Input::get('nama_estimasi');
$data->total = $total;
$data->trigger_bom = Input::get('trigger_bom');
$data->save();
}
}
My View
<td><input type="text" name="quantity[]" class="form-control"></td>
<td><input type="text" name="kode_proyek" hidden value="{{$panel->kode_projek}}">
etc....
My View
my view
You can save it first to array then use bulk insert.
Inserting data 1 by 1 will slow your application.
$insertArray = array();
foreach($request->quantity as $quantity){
if($quantity == NULL){
$insertArray[] = array(
'quantity' => $quantity,
'harga_satuan_mu ' => Input::get('harga_satuan_mu'),
.... // add other fields
)
}
}
KomponenOlahan::insert($insertArray);

Get sum of multiplication of two column values from unrelated tables in cart

In my laravel ecommerce project
I have 2 tables in the database :
cart [c_id(pk), laundry, l1, dryclean, dc1, dc2, dc3, shop_id]
price [p_id, p_l1, p_dc1, p_dc2, p_dc3, shop_id]
In controller I get prices of logged in shop i.e. single row
$price = DB::table('price')->where('price.shop_id', '=', auth()->id())->get();
also to get a row from cart table I am taking the most recent entry
$cart = DB::table('cart')->latest()->first();
Laundry and dryclean columns from cart table can have two values YES and NO. If laundry is yes then user also enters l1(which is quantity) else null.
similarly, for dryclean column can have two values YES and NO. If YES then user also enters dc1, dc2, dc3(quantities of items).
Now I want to get the Total amount on checkout page from controller including conditions where values of laundry and dryclean are checked.
So far I was calculating total in the view file.
#if ( $cart->dryclean == "no")
#php $c1=0;$c2=0;$c3=0; #endphp
#else
#if (is_null($cart->dc1))
#php $c1=0; #endphp
#else
#php
$a1= $cart->dc1;
$b1 =$price->p_dc1;
$c1= $a1*$b1;
#endphp
#endif
#if (is_null($cart->dc2))
#php $c2=0; #endphp
#else
#php
$a2= $cart->dc2;
$b2 =$price->p_dc2;
$c2= $a2*$b2;
#endphp
#endif
#if (is_null($cart->dc3))
#php $c3=0; #endphp
#else
#php
$a3= $cart->dc3;
$b3 =$price->p_dc3;
$c3= $a3*$b3;
#endphp
#endif
{{ $c1 + $c2 + $c3}} <!-- This is total amount -->
#endif
Please help me writing controller queries to calculate total amount in controller itself and display in the view.
Thanks in advance.
Just remove the blade syntax of everything you did.
if ( $cart->dryclean == "no" ) {
$c1 = 0;
$c2 = 0;
$c3 = 0;
} else {
if ( is_null($cart->dc1) ) {
$c1 = 0;
} else {
$a1 = $cart->dc1;
$b1 = $price->p_dc1;
$c1 = $a1 * $b1;
}
if ( is_null($cart->dc2) ) {
$c2 = 0;
} else {
$a2 = $cart->dc2;
$b2 = $price->p_dc2;
$c2 = $a2 * $b2;
}
if ( is_null($cart->dc3) ) {
$c3 = 0;
} else {
$a3 = $cart->dc3;
$b3 = $price->p_dc3;
$c3 = $a3 * $b3;
}
// total used to be calculated here
}
$total = $c1 + $c2 + $c3;
return view('your.view.here')->with('total', $total);
Some tips, based on what I see:
Use a Boolean value in the $cart->dryclean field. This is easier to store and use than "yes" and "no".
You were calculating the total in blade before you got to the end of your first"if" statement. If the dryclean value was no (or false), no total would have been given.
For your own readability, I recommend using the full name, such as $cost1. I actually can't even tell if that is your intention because it just says 'c1'..
You can bypass many of the calculations by using the null coalesce operator to give a default value if the first one is null.
If you take my tips, you could have your controller be like the example below.
if ( $cart->dryclean ) {
$cost1 = ($cart->dc1 ?? 0) * $price->p_dc1;
$cost2 = ($cart->dc2 ?? 0) * $price->p_dc2;
$cost3 = ($cart->dc3 ?? 0) * $price->p_dc3;
} else {
$cost1 = 0;
$cost2 = 0;
$cost3 = 0;
}
$total = $cost1 + $cost2 + $cost3;
return view('your.view.here')->with('total', $total);
If you wanted to take it a step further, you could do this (using the ternary operator):
// set class properties
$this->cart = $cart;
$this->price = $price;
$total = ( $cart->dryclean )
? $this->costOf('1') + $this->costOf('2') + $this->costOf('3')
: 0;
return view('your.view.here')->with('total', $total);
Of course, this is using another private function outside of the original controller function:
private funtion costOf($number)
{
return ( $this->cart->{'dc'.$number} ?? 0 ) * $this->price->{'p_dc'.$number};
}
This costOf function is using the string version of the number to grab the associated fields on each model type.

Grails Sorting Giving me hard times

Sort of new to grails! I am currently working on grails 2.3.11 and I can't see why the following code is not working as intended!
def listCommodity() {
List<Commodity> commodities;
if (params.searchBox) {
commodities = Commodity.list().findAll {
it.name.toLowerCase().contains("${params.searchBox.toLowerCase()}") ||
it.type.name.toLowerCase().contains("${params.searchBox.toLowerCase()}") ||
(it.type.parent ? it.type.parent.name.toLowerCase().contains("${params.searchBox.toLowerCase()}") : false)
}
} else {
commodities = Commodity.list()
}
commodities?.sort { one, two ->
if ("decs" == params?.order) {
return two.name <=> one.name
} else {
return one.name <=> two.name
}
}
def max = Math.min((params.max ?: 10) as Long, 100)
def offset = Math.min((params.offset ?: 0) as Long, commodities.size() - 1)
if (!commodities) {
flash.message = "No Items found Here!"
return [commodities: [], commoditiesCount: 0]
} else {
return [commodities: commodities[offset..Math.min(offset + max, commodities.size() - 1)], commoditiesCount: commodities.size(), searchBoxText: params.searchBox ?: '']
}
}
view:
....
<tr>
<g:sortableColumn params="${[searchBox:searchBoxText]}" property="name" title="${message(code: 'commodity.commodity.name.label', default: 'Name')}" />
</tr>
....
<% println commodities //here it prints the items in ascending %>
<g:each in="${commodities}" status="i" var="com">
<tr class="${(i % 2) == 0 ? 'even' : 'odd'}">
<td>
${com?.getName(lang)}
</td>
</tr>
</g:each>
....
this test passes:
given:
mockDomain(CommodityType,[[name: "Cereals"],[name: "Group", parent: new CommodityType(name: 'Corea')]])
mockDomain(Commodity,
[[name:"Kea", type:CommodityType.findByName("Cereals")],
[name:"Shiro", type:CommodityType.findByName("Cereals")],
[name:"Other with ea", type:new CommodityType(name: "Grass")],
[name:"Barely", type:CommodityType.findByName("Group")],
[name:"Teff",type:CommodityType.findByName("Cereals")]])
when:
params.order = "decs"
params.searchBox = "ea"
def models = controller.listCommodity()
then:
5 == models.commodities.size()
"Barely" == models.commodities[-1].name
"Teff" == models.commodities[0].name
"ea" == models.searchBoxText
when:
params.order = "asc"
params.searchBox = "ea"
def models2 = controller.listCommodity()
then:
5 == models2.commodities.size()
"Barely" == models2.commodities[0].name
"Teff" == models2.commodities[-1].name
"ea" == models2.searchBoxText
but when i test it on the browser! The sorting doesn't do anything! The i did a println on the view and the list is never sorted! What am i doing wrong?
Two things to check :
use sort(boolean, closure) with true in the 1st argument to sort the list itself, otherwise a copy is created
the standard parameter is "desc" not "decs"
Good luck!

How to make this Razor View work like the ASPX one does?

I have been struggling to get a partial View working in Razor. The View engine cannot make sense of the code below but it is simple using the ASPX View engine. Can anyone show me how to get this to work with Razor? Note that I am just writing out a calendar so the <tr> tag happens at the end of every week. The first sign of a problem is that the Razor code will not format in the VS editor and it complains that the 'while' block is missing its closing brace. I have tried all kinds of combinations, even using a delegate. (I think the cause of the problem may be the conditional TR tag because it is highlighted as an error because it is not closed.)
Razor (doesn't work)
<table class="calendarGrid">
<tr class="calendarDayNames">
<th>Monday</th>
<th>Tuesday</th>
<th>Wednesday</th>
<th>Thursday</th>
<th>Friday</th>
<th>Saturday</th>
<th>Sunday</th>
</tr>
#{
var loopDate = gridStartDate;
}
#while (loopDate <= gridEndDate)
{
if (loopDate.DayOfWeek == DayOfWeek.Monday)
{
<tr class="calendarWeek">
}
<td class="calendarDay">
<span class="calendarDayNumber">#loopDate.Day</span>
#if (Model.AllCalendarDays.ContainsKey(loopDate.Date))
{
foreach (var ev in Model.AllCalendarDays[loopDate.Date])
{
<span class="calendarEvent">#ev.Venue</span>
}
}
</td>
#{
loopDate = loopDate.AddDays(1);
#if (loopDate.DayOfWeek == DayOfWeek.Monday)
{
</tr>
}
}
}
ASPX (works)
<table class="calendarGrid">
<tr class="calendarDayNames">
<th>Monday</th>
<th>Tuesday</th>
<th>Wednesday</th>
<th>Thursday</th>
<th>Friday</th>
<th>Saturday</th>
<th>Sunday</th>
</tr>
<%
var loopDate = gridStartDate;
while (loopDate <= gridEndDate)
{
if (loopDate.DayOfWeek == DayOfWeek.Monday)
{
%>
<tr class="calendarWeek">
<%} %>
<td class="calendarDay">
<span class="calendarDayNumber">
<%: loopDate.Day %></span>
<% if (Model.AllCalendarDays.ContainsKey(loopDate.Date))
{
foreach (var ev in Model.AllCalendarDays[loopDate.Date])
{ %>
<span class="calendarEvent">
<%: ev.Venue %></span>
<% }
} %>
</td>
<% {
loopDate = loopDate.AddDays(1);
if (loopDate.DayOfWeek == DayOfWeek.Monday)
{ %>
</tr>
<% }
}
} %>
</table>
Working solution in Razor based on #jgauffin's view model suggestion and #dommer's ugly raw html solution. Combined together they're almost aesthetically acceptable. :)
View model now has iterator
public IEnumerable<Tuple<DateTime, IList<CalendarEventDto>>> GridItems()
{
var loopDate = GridStartDate;
while (loopDate <= GridEndDate)
{
yield return new Tuple<DateTime, IList<CalendarEventDto>>(loopDate.Date, AllCalendarDays[loopDate.Date]);
loopDate = loopDate.AddDays(1);
}
}
Okay, the Tuple is lazy but I will probably create another model to hold more complex information about the date and events (IsPast/greyed, etc).
The pesky View
#foreach (var item in Model.GridItems())
{
if (item.Item1.DayOfWeek == DayOfWeek.Monday)
{
#Html.Raw("<tr class=\"calendarWeek\">");
}
#Html.Raw("<td class=\"calendarDay\">");
#Html.Raw(string.Format("<span class=\"calendarDayNumber\">{0}</span>", item.Item1.Day));
foreach (var ev in item.Item2)
{
#Html.Raw(string.Format("<span class=\"calendarEvent\">{0}</span>", Server.HtmlEncode(ev.Venue)));
}
#Html.Raw("</td>");
if (item.Item1.DayOfWeek == DayOfWeek.Sunday)
{
#Html.Raw("</tr>");
}
}
Note that when I reformat the View source in VS, it gets egregiously tabbed, with the if statement having about 10 tabs to the left of it, but there are no compilation warnings and it does what I want. Not nice, or easy though. I think the Razor devs should provide some support for explicit breakout and breakin to code and markup so that when the parser cannot parse it unambiguously, we can tell it what we intended.
#Andrew Nurse's solution
Andrew 'works on the ASP.Net team building the Razor parser!'. His solution runs okay but still produces compiler warnings and is obviously confusing Visual Studio because the code cannot be reformatted without ending up in a big glob on a few lines:
<tbody>
#foreach (var calDay in Model.GridItems())
{
if (calDay.DayOfWeek == DayOfWeek.Monday)
{
#:<tr class="calendarWeek">
}
<td class="calendarDay">
<span class="calendarDayNumber">#calDay.Day</span>
#foreach (var ev in calDay.CalendarEvents)
{
<span class="calendarEvent">#ev.Venue</span>
}
</td>
if (calDay.DayOfWeek == DayOfWeek.Sunday)
{
#:</tr>
}
}
</tbody>
The primary issues here were these lines:
if (loopDate.DayOfWeek == DayOfWeek.Monday)
{
<tr class="calendarWeek">
}
...
#if (loopDate.DayOfWeek == DayOfWeek.Monday)
{
</tr>
}
The problem is that Razor uses the tags to detect the start and end of markup. So since you didn't close the "tr" tag inside the first if, it doesn't actually switch back to code, so it doesn't see the "}" as code. The solution is to use "#:", which lets you put a line of markup without regard for tags. So replacing those lines with this should work and be more concise than using Html.Raw:
if (loopDate.DayOfWeek == DayOfWeek.Monday)
{
#:<tr class="calendarWeek">
}
...
#if (loopDate.DayOfWeek == DayOfWeek.Monday)
{
#:</tr>
}
I would move all logic to the viewmodel which leaves the following code in your view:
#while (Model.MoveNext())
{
#Model.WeekHeader
<td class="calendarDay">
<span class="calendarDayNumber">#Model.DayNumber</span>
#foreach (var ev in Model.CurrentDayEvents)
{
<span class="calendarEvent">#ev.Venue</span>
}
</td>
#Model.WeekFooter
}
And the new model:
public class CalendarViewModel
{
private DateTime _currentDate;
public string WeekHeader
{
get
{
return _currentDate.DayOfWeek == DayOfWeek.Monday ? "<tr class="calendarWeek">" : "";
}
}
public string WeekFooter
{
get
{
return _currentDate.DayOfWeek == DayOfWeek.Monday ? "</tr>" : "";
}
}
public IEnumerable<DayEvent>
{
get
{
return AllCalendarDays.ContainsKey(loopDate.Date) ? AllCalendarDays[loopDate.Date] ? new List<DayEvent>();
}
}
public bool MoveNext()
{
if (_currentDate == DateTime.MinValue)
{
_currentDate = gridStartDate;
return true;
}
_currentDate = _currentDate.AddDays(1);
return _currentDate <= gridEndDate;
}
}
MAJOR EDIT: Okay, what happens if you do this?
<table class="calendarGrid">
<tr class="calendarDayNames">
<th>Monday</th>
<th>Tuesday</th>
<th>Wednesday</th>
<th>Thursday</th>
<th>Friday</th>
<th>Saturday</th>
<th>Sunday</th>
</tr>
#{
var loopDate = gridStartDate;
while (loopDate <= gridEndDate)
{
if (loopDate.DayOfWeek == DayOfWeek.Monday)
{
#Html.Raw("<tr class=\"calendarWeek\">");
}
#Html.Raw("<td class=\"calendarDay\">");
#Html.Raw("<span class=\"calendarDayNumber\">" + loopDate.Day + "</span>");
if (Model.AllCalendarDays.ContainsKey(loopDate.Date))
{
foreach (var ev in Model.AllCalendarDays[loopDate.Date])
{
#Html.Raw("<span class=\"calendarEvent\">" + ev.Venue + "</span>");
}
}
#Html.Raw("</td>");
loopDate = loopDate.AddDays(1);
if (loopDate.DayOfWeek == DayOfWeek.Monday)
{
#Html.Raw("</tr>");
}
}
}
Have you tried adding <text> tags around the contents of the blocks?
I think the Razor parse only works when it's obvious where the blocks end. It may be getting confused by the fact you have an if, a td and then some more code, all inside the block.
There's more info on this here: http://weblogs.asp.net/scottgu/archive/2010/12/15/asp-net-mvc-3-razor-s-and-lt-text-gt-syntax.aspx

prototype findElements querySelectorAll error

i'm call the "down" function but am getting an invalid argument using 1.6.1_rc2
here's the html snippet:
<TR id=000000214A class="activeRow searchResultsDisplayOver" conceptID="0000001KIU">
<TD>
<DIV class=gridRowWrapper>
<SPAN class=SynDesc>Asymmetric breasts</SPAN>
<DIV class=buttonWrapper>
<SPAN class=btnAddFav title="Add to Favorites"> </SPAN>
</DIV>
</DIV>
</TD>
</TR>
here's the code:
var description = row.down('span.SynDesc').innerHTML;
row is a dom reference to the element.
prototype is appending a # then the id of the element:
findElements: function(root) {
root = root || document;
var e = this.expression, results;
switch (this.mode) {
case 'selectorsAPI':
if (root !== document) {
var oldId = root.id, id = $(root).identify();
id = id.replace(/[\.:]/g, "\\$0");
e = "#" + id + " " + e;
}
results = $A(root.querySelectorAll(e)).map(Element.extend); <-- e = "#000000214A span.SynDesc"
root.id = oldId;
return results;
case 'xpath':
return document._getElementsByXPath(this.xpath, root);
default:
return this.matcher(root);
}
i get an "invalid argument" error?
if i put a breakpoint before the offending line and change e to be equal to "span.SynDesc" it works fine.
help. :)
I ran into this. Changing the TR's ID to start with a letter should fix the problem. It turns out that legal HTML IDs match /^[A-Za-z][A-Za-z0-9_:.-]*$/.

Resources