laravel unable to parse data - laravel-routing

I want to go to page edit from PayAbleIndex to PayAbleEdit.
On laravel 5.4 i could use:
<button class="btn btn-primary">Edit</button>.
But currently I'm working on laravel 5.7 and i copy same code but laravel couldn't get any data from it.
My blade.php
#foreach($purchase as $data)
<tr>
<td>{{ $data->id }}</td>
<td>{{ $data->created_at }}</td>
<td>#if($data->import == 'y')Yes #else No #endif</td>
<td>Edit {{ $data->id }}</td>
</tr>
#endforeach
my controller
public function edit(accountPayAble $accountPayAble)
{
$pa = accountPayAble::where('purchases',$accountPayAble->id)->get();
return view('pages.payAbleEdit',['pa' => $pa]);
}
My accountPayAble Primary key are not ID but purchases
my account payable model
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class accountPayAble extends Model
{
protected $table = "account_pay_ables";
protected $primaryKey = 'purchases';
public $timestamps =false;
public function purchase(){
return $this->belongsTo('App\purchase','purchases');
}
}

I think controller return array name should be purchase as below
public function edit(accountPayAble $accountPayAble)
{
$pa = accountPayAble::where('purchases',$accountPayAble->id)->get();
return view('pages.payAbleEdit',['purchase' => $pa]);
}
Check this and if it is not possible comment below.

Here is how generally edit method works
If you're passing id in edit method parameter in blade like this
Edit {{ $data->id }}
In this case route must have /{id}
// If you are using resource route then it will add /{id} in your edit parameter
Route::resource('payable', 'AccountPayAble');
// If you've defined custom route then
Route::get('/payable/edit/{id}','AccountPayAble#edit')->name('payable.edit');
In Your controller
// then you need to pass as well in your Controller method
public function edit(Request $request, $id)
{
$ap = AccountPayAble::find($id);
// OR
$ap = AccountPayAble::where('primary_key',$id)->first();
return view('pages.payAbleEdit',compact('ap'));
}
// If you've primary key other than id then define key into your model
protected $primaryKey = 'your_key_name';
I hope this helps.

Related

I Want to Put String on URL for HTTP CLIENT API LARAVEL 8

my View :
<td>{{ $b = $booking->tanggal_pemesanan }}</td>
<td>CEK</td>
Route :
Route::get('/{b}', [TestController::class, 'index']);
my Controller:
public function index()
{
return Http::get('https://wetonizer-api.herokuapp.com/{b}');
}
did i do wrong? please help....
What is the actual return of $booking->tanggal_pemesanan?
Try using;
<td>CEK</td>
In your Controller;
index function should have ($b) to understand/know what is {b}
Then it should work

How to export PDF from back-end edit/update view using DynamicPDF plugin in OctoberCMS

I am going to use DynamicPDF plugin to export to pdf some fields from backend on update/edit view of my plugin in OctoberCMS, can someone help me?
on plugin controller i have this call:
<?php namespace Vimagem\Pacientes\Controllers;
use Backend\Classes\Controller;
use BackendMenu;
use Renatio\DynamicPDF\Classes\PDF;
use Renatio\DynamicPDF\Classes\PDFWrapper;
class Pacientes extends Controller
{
public $implement = [ 'Backend\Behaviors\ListController', 'Backend\Behaviors\FormController', 'Backend\Behaviors\ReorderController' ];
public $listConfig = 'config_list.yaml';
public $formConfig = 'config_form.yaml';
public $reorderConfig = 'config_reorder.yaml';
public function __construct()
{
parent::__construct();
BackendMenu::setContext('Vimagem.Pacientes', 'main-menu-item');
}
/** PDF **/
public function pdf($id)
{
return PDF::loadTemplate('export-data-pdf')->stream('download.pdf');
}
}
On the PDF Template (export-data-pdf) i need to call some form fields from one client:
{{ name }}
{{ address }}
{{ phone }}
etc...
but i canĀ“t get the fields show up, what its wrong ?
Thank you,
Vitor
This code was found in the plugins documents.
use Renatio\DynamicPDF\Classes\PDF; // import facade
...
public function pdf()
{
$templateCode = 'renatio::invoice'; // unique code of the template
$data = ['name' => 'John Doe']; // optional data used in template
return PDF::loadTemplate($templateCode, $data)->stream('download.pdf');
}
I have used this plugin and it works well. You need to pass in data to the PDF stream.
This is done, worked around a solution for this.
Here is the controller application:
<?php namespace Vimagem\Pacientes\Controllers;
use Backend\Classes\Controller;
use BackendMenu;
use Renatio\DynamicPDF\Classes\PDFWrapper;
use Vimagem\Pacientes\Models\Paciente;
use \October\Rain\Database\Traits\Validation;
use Str;
class Pacientes extends Controller
{
public $implement = [ 'Backend\Behaviors\ListController', 'Backend\Behaviors\FormController', 'Backend\Behaviors\ReorderController' ];
public $listConfig = 'config_list.yaml';
public $formConfig = 'config_form.yaml';
public $reorderConfig = 'config_reorder.yaml';
public function __construct()
{
parent::__construct();
BackendMenu::setContext('Vimagem.Pacientes', 'main-menu-item');
}
/**** PDF Export ***/
public function pdf($id)
{
$paciente = Paciente::find($id);
if ($paciente === null) {
throw new ApplicationException('User not found.');
}
$filename = Str::slug($paciente->nome) . '.pdf';
try {
/** #var PDFWrapper $pdf */
$pdf = app('dynamicpdf');
$options = [
'logOutputFile' => storage_path('temp/log.htm'),
];
return $pdf
->loadTemplate('export-data-pdf', compact('paciente'))
->setOptions($options)
->stream($filename);
} catch (Exception $e) {
throw new ApplicationException($e->getMessage());
}
}
}
Now i can use partials on the template like this:
<p>{{ paciente.nome }}</p>
<p>{{ paciente.morada }}</p>
etc...
Thank you all that try to helped me.
Vitor

Aurelia Dynamically Bound Value Converter

I'm running into an issue with Aurelia and am assuming that there is something I am missing.
I'm trying to create a 'generic' grid. I have removed a lot of the html to keep the example short, but the basic idea is this:
<template>
<require from="../value-converters"></require>
<table show.bind="rows.length">
<thead>
<tr>
<th repeat.for="columnDefinition of columnDefinitions">
${columnDefinition.displayName}
</th>
</tr>
</thead>
<tbody>
<tr repeat.for="row of rows">
<td repeat.for="columnDefinition of columnDefinitions">
<span if.bind="columnDefinition.isCurrency">${row[columnDefinition.propertyName] | numeralFormatter}</span>
<span if.bind="columnDefinition.isDate">${row[columnDefinition.propertyName] | dateFormatter}</span>
<span if.bind="!columnDefinition.isCurrency && !columnDefinition.isDate &&">${row[columnDefinition.propertyName]}</span>
</td>
</tr>
</tbody>
</table>
</template>
I want to be able to use the ValueConverters to help properly display certain types of column data. The above is currently working, but I want to have more value converters for other columns and the conditions will get unwieldy. My experience with Aurelia so far is that it offers fairly elegant solutions, but I have been unable to figure this one out as of yet.
I tried adding another property to the columnDefinition class like this formatter:string = undefined and then tried to create the spans like the following:
<span if.bind="columnDefinition.formatter">${row[columnDefinition.propertyName] | columnDefinition.formatter}</span>
<span if.bind="!columnDefinition.formatter">${row[columnDefinition.propertyName]}</span>
but the parser threw an error on the '.'.
Is there any way to achieve this? What is the 'aurelia-way' of dealing with this type of a problem.
Thanks in advance for any help that could be offered.
I ended up taking a similar approach to the one suggested by #Slyvain with a bit of a different twist:
import {DateValueConverter} from './date';
import {NumberValueConverter} from './number';
import {autoinject} from 'aurelia-framework';
#autoinject()
export class MetaValueConverter {
constructor(private date: DateValueConverter,
private number: NumberValueConverter) {
}
public toView(value, valueConverter, format) {
/* JUSTIFICATION: https://stackoverflow.com/questions/38898440/aurelia-dynamically-bound-value-converter#comment-65199423 */
/* tslint:disable:no-string-literal */
if (this[valueConverter] && this[valueConverter].toView) {
return this[valueConverter].toView(value, format);
} else {
return value;
}
}
public fromView(val, valueConverter, format) {
if (this[valueConverter] && this[valueConverter].fromView) {
return this[valueConverter].fromView(value, format);
} else {
return value;
}
}
}
Original code can be found here.
Hope this helps.
I followed #peinearydevelopment and went one step further again to create a fully dynamic value converter.
Usage is as follows ${myValue | dynamic:converterKey:converterArgs} or simply ${myValue | dynamic:converterKey} if no additional arguments are required. The converterKey is used to request a value converter that should be registered with the container. converterArgs is the array of arguments that you'd pass to the toView & fromView functions.
import { autoinject, Container } from 'aurelia-dependency-injection';
export type ValueConverterKey = new (...args: any[]) => object;
type ValueConverterFunc = (...args: any[]) => any;
interface ValueConverter {
toView?: ValueConverterFunc;
fromView?: ValueConverterFunc;
}
#autoinject()
export class DynamicValueConverter {
constructor(
private container: Container,
) { }
public toView(value: any, converterKey?: ValueConverterKey, ...converterArgs: any[]) {
if (!converterKey) {
return value;
}
return this.convertValueIfPossible(value, converterKey, converterArgs, 'toView');
}
public fromView(value: any, converterKey?: ValueConverterKey, ...converterArgs: any[]) {
if (!converterKey) {
return value;
}
return this.convertValueIfPossible(value, converterKey, converterArgs, 'fromView');
}
private convertValueIfPossible(value: any, converterKey: ValueConverterKey, converterArgs: any[], func: keyof ValueConverter) {
let converter = this.container.get(converterKey);
if (converter) {
let converterFunc = converter[func];
if (converterFunc) {
return converterFunc.call(converter, value, ...converterArgs);
}
}
return value;
}
}
Have you considered using a single <span> with a single general purpose converter that takes the column definition as a parameter and that delegates to the right converter? I think that would make the component markup simpler.
<span>${row[columnDefinition.propertyName] | formatCell:columnDefinition}</span>
And inside the formatter:
export class FormatCell {
toView(value, columnDefinition){
if(columnDefinition.isCurrency)
return new CurrencyConverter().toView(value);
if(columnDefinition.isDate)
return new DateConverter().toView(value);
return value;
}
}

Wicket dynamicly add data from database to page

I'm trying to add some data into page from database, after applying "filter"
After submit form, candidate list is update and I want to push this changes into page.
How can I do this in wicket ?
.java file
public class SearchCandidate extends WebPage {
private SearchCandidateModel searchCandidateModel = new SearchCandidateModel();
private List<CandidateEntity> candidate = new ArrayList();
public SearchCandidate(PageParameters p) {
super(p);
final TextField<String> firstName = new TextField<>("first_name", new PropertyModel<String>(searchCandidateModel, "firstName")); //Filter
final DataView dataView = new DataView("simple", new ListDataProvider(candidate)) {
public void populateItem(final Item item) {
final CandidateEntity user = (CandidateEntity) item.getModelObject();
item.add(new Label("firstName", user.getFirstName()));
}
};
Form<?> form = new Form<Void>("step1") {
#Override
protected void onSubmit() {
candidate = databse.findCandidate(searchCandidateModel.getFirstName());
//UPDATE TABLE
}
};
form.add(firstName);
add(form);
add(dataView);
}
}
html file:
<form wicket:id="step1">
<input wicket:id="first_name" type="text" size="30"/>
</form>
<table cellspacing="0" class="dataview">
<tbody>
<tr wicket:id="simple">
<td><span wicket:id="name">Test ID</span></td>
</tr>
</tbody>
</table>
You can make you DataProvider - dynamic:
new ListDataProvider() {
#Override protected List getData() {
if (noFilter) return emptyList
else return database.getList(filter)
}
}
This way the provider will always load the data according to your data filter.
For more information about static vs. dynamic models/providers check:
https://cwiki.apache.org/confluence/display/WICKET/Working+with+Wicket+models#WorkingwithWicketmodels-DynamicModels

Url.Action is how to reformat URL

I am creating an MVC4 application.
In my contract controller overview page i have an Url.Action
int teller = 0;
foreach (var item in Model)
{
<a href="#Url.Action("Details", "Contract",new { id = teller })">
<tr>
<td>#Html.DisplayFor(modelItem => item.ContractMSFNo)</td>
<td>#Html.DisplayFor(modelItem => item.StageCode)</td>
<td>#Html.DisplayFor(modelItem => item.ValidFromView)</td>
<td>#Html.DisplayFor(modelItem => item.ValidToView)</td>
</tr>
</a>
teller++;
}
I need to pass the id. I am using id in the ActionLink details in Contract Controller
my controller is
public ActionResult Details(int id)
{
//code
return View(contract);
}
When i click on the link Url generated is
http://localhost:4826/Contract/Details/0
/0 is the id
i want my Url to be http://localhost:4826/Contract/Details
i know this can be acheived thru Html.Actionlink but it is my compulsion to use Url.Action. Can it be acheived with Url.Action
It can't be done by routing or ActionLink. But you may try to use session.
1) Add to your controller new method to save your id to session:
public JsonResult Save(int id)
{
Session["ID"] = id;
return Json("Success");
}
2) Add jQuery method to save data in session from View and delete parameter from Url.Action:
<a class="mylink" href="#Url.Action("Details", "Contract")"></a>
<script>
$(".mylink").click(function(){
var data = { id : teller}; //**teller is from your example
$.get("#Url.Action("Details", "Contract")", data)
});
</script>
3) Change your Details ActionResult to get id from session:
public ActionResult Details()
{
var id = (int)Session["ID"];
//code
return View(contract);
}
P.S: Ask your client, how he expects to give sombody external links. It will be impossible if url doesn't have a parameter. And it is very bad for SEO.
If you want your URL without the id parameter, simply don't pass it to the Url.Action() method, as follows:
#Url.Action("Details", "Contract")
If you add like {id=teller} then route automatically add id parameters end of the link. If you don't need id parameters for this url you need to remove
new { id = teller }
Final version like this
#Url.Action("Details", "Contract")
OK, reading this comment: "no actually there are many ids ... code is foreach (var item in Model) { ", I am not sure I understand what you really want to achieve. You are passing a parameter to the view, which can have only one value. Are you sure that you are not looking for something like:
foreach (var item in Model)
{
<a href="#Url.Action("Details", "Contract",#item.ID>
...
}
instead? The fact the ID is visible or not in the URL seems to be another problem, no ?