Blade to PDF passing variables - laravel
I have this blade view that retrieves data from a controller. So far, so good. Now I need to export this view to a PDF, but can't pass any variables.
Let's see some code:
My controller:
public function nota(Request $request)
{
$pessoa = Contrato::where('user_id', '=', Auth::user()->id)->first();
$contrato = Contrato::where('user_id', '=', Auth::user()->id)
->where('disponivel', '=', 1)->get();
$endereco = Endereco::where('user_id', '=', Auth::user()->id)->first();
$consorciado = Auth::user();
$data = [$pessoa, $contrato, $endereco, $consorciado];
$pdf = PDF::loadView('contemplado.notaPromissoria', compact('data'));
return $pdf->download('notapromissoria.pdf');
// return view('contemplado.notaPromissoria')->withPessoa($pessoa)->withContrato($contrato)->withEndereco($endereco)->withConsorciado(Auth::user());
}
My blade:
#extends('contemplado.app')
#section('content')
<div class="container m-t-50">
<div class="container">
<h4>Nota Promissória</h4>
<div class="card">
<div class="card-body">
<div class="row">
<div class="col-sm-6">
{{-- Emitente: <strong>{{ $consorciado->name }}</strong> --}}
</div>
<div class="col-sm-6">
Contrato número:
#foreach($contrato as $c)
<strong>{{ $c->contrato }}</strong>
#endforeach
</div>
</div>
#foreach($contrato as $c)
<div class="row">
<div class="col-sm-6">Percentual Vincendo: <strong>{{ $c->percQuitacao }} %</strong></div>
<div class="col-sm-6">Grupo: <strong>{{ $c->grupo }}</strong>, Cota: <strong>{{ $c->cota }}</strong></div>
</div>
#endforeach
#foreach($contrato as $c)
Valor: <strong>R$ {{ $c->valor }}</strong><br>
<div class="row">
<div class="col-sm-4">
Aos dias
<hr class="m-t-10 new3">
</div>
<div class="col-sm-4">
do mês de
<hr class="m-t-10 new3">
</div>
<div class="col-sm-4">
de
<hr class="m-t-10 new3">
</div>
</div>
<div class="row m-t-10">
<div class="col-sm-12">
, pagarei por esta <strong>NOTA PROMISSÓRIA</strong> ao <strong>PRIMO ROSSI ADM DE CONSÓRCIO LTDA</strong> ou à sua ordem a quantia de:<small><i>(por extenso)</i></small>
<hr class="m-t-10 new3"> em moeda corrente, no valor correspondente ao saldo devedor a data de:{DATA DO DIA DA EMISSÃO}
</div>
</div>
#endforeach
<hr>
<div class="row m-b-20">
<div class="col-sm-12">
<strong>Esta Nota Promissória é inegociável, conforme contrato de alienação fiduciária e/ou escritura pública de confissão de dívida com garantia hipotecária, a qual está vinculada, fazendo parte integrante e inseparável dos mesmos</strong>
</div>
</div>
</div>
<div class="card-body">
<div class="row">
<div class="col-sm-6">
{{-- Nome: <strong>{{ $consorciado->name }}</strong> --}}
</div>
<div class="col-sm-6">
{{-- CPF/CNPJ: <strong>{{ $consorciado->cpfCnpj }}</strong> --}}
</div>
</div>
<div class="row">
<div class="col-sm-12">
Endereço: <strong>{{ $endereco->logradouro }}</strong>, <strong>{{ $endereco->numero }}</strong>
</div>
</div>
<div class="row">
<div class="col-sm-6">
Cidade: <strong>{{ $endereco->municipio }}</strong>
</div>
<div class="col-sm-6">
Estado: <strong>{{ $endereco->uf }}</strong>
</div>
</div>
<div class="row">
<div class="col-sm-6">
CEP: <strong>{{ $endereco->cep }}</strong>
</div>
<div class="col-sm-6">
Telefones: <strong>{{ $endereco->telefone }}</strong> <strong>{{ $endereco->celular }}</strong>
</div>
</div>
<div class="row">
<div class="col-sm-12">
Assinatura Emitente:<br>
<hr class="m-t-10 new3">
</div>
</div>
</div>
<div class="card-body">
<div class="card-tile">
<strong>Primeiro Avalista</strong>
</div>
<div class="row">
<div class="col-sm-6">
Nome:
<hr class="m-t-10 new3">
</div>
<div class="col-sm-6">
CPF:
<hr class="m-t-10 new3">
</div>
</div>
<div class="row">
<div class="col-sm-12">
Endereço:
<hr class="m-t-10 new3">
</div>
</div>
<div class="row">
<div class="col-sm-6">
Cidade:
<hr class="m-t-10 new3">
</div>
<div class="col-sm-6">
Estado:
<hr class="m-t-10 new3">
</div>
</div>
<div class="row">
<div class="col-sm-6">
CEP:
<hr class="m-t-10 new3">
</div>
<div class="col-sm-6">
Telefones:
<hr class="m-t-10 new3">
</div>
</div>
<div class="row">
<div class="col-sm-12">
Assinatura do Avalista:<br>
<hr class="m-t-10 new3">
</div>
</div>
<div class="row">
<div class="col-sm-6">
Nome do Cônjuge:
<hr class="m-t-10 new3">
</div>
<div class="col-sm-6">
CPF do Cônjuge:
<hr class="m-t-10 new3">
</div>
</div>
<div class="row m-t-10">
<div class="col-sm-12">
Assinatura do Cônjuge do Avalista:<br>
<hr class="m-t-10 new3">
</div>
</div>
<hr>
<div class="card-tile">
<strong>Segundo Avalista</strong>
</div>
<div class="row">
<div class="col-sm-6">
Nome:
<hr class="m-t-10 new3">
</div>
<div class="col-sm-6">
CPF:
<hr class="m-t-10 new3">
</div>
</div>
<div class="row">
<div class="col-sm-12">
Endereço:
<hr class="m-t-10 new3">
</div>
</div>
<div class="row">
<div class="col-sm-6">
Cidade:
<hr class="m-t-10 new3">
</div>
<div class="col-sm-6">
Estado:
<hr class="m-t-10 new3">
</div>
</div>
<div class="row">
<div class="col-sm-6">
CEP:
<hr class="m-t-10 new3">
</div>
<div class="col-sm-6">
Telefones:
<hr class="m-t-10 new3">
</div>
</div>
<div class="row">
<div class="col-sm-12">
Assinatura do Avalista:<br>
<hr class="m-t-10 new3">
</div>
</div>
<div class="row">
<div class="col-sm-6">
Nome do Cônjuge:
<hr class="m-t-10 new3">
</div>
<div class="col-sm-6">
CPF do Cônjuge:
<hr class="m-t-10 new3">
</div>
</div>
<div class="row m-t-10">
<div class="col-sm-12">
Assinatura do Cônjuge do Avalista:<br>
<hr class="m-t-10 new3">
</div>
</div>
</div>
</div>
</div>
</div>
#endsection
#section('scripts')
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script>
var vue = new Vue({
el: '#app',
data: {
isLoading: false
},
});
</script>
#endsection
The print_r result:
Array ( [0] => App\Contrato Object ( [guarded:protected] => Array ( ) [connection:protected] => mysql [table:protected] => contratos [primaryKey:protected] => id [keyType:protected] => int [incrementing] => 1 [with:protected] => Array ( ) [withCount:protected] => Array ( ) [perPage:protected] => 15 [exists] => 1 [wasRecentlyCreated] => [attributes:protected] => Array ( [id] => 459 [user_id] => 842 [contrato] => 851717 [disponivel] => 1 [grupo] => 06271 [cota] => 871 [valor] => 34163 [conta_conjunta] => [novoSegmento] => [originalSegmento] => 06271 [completo] => [novoUsado] => 1 [pessoa] => F [descricao] => 50% COBALT 1.8 (COD.9062) [data_entrega] => 1970-01-01 00:00:01 [data_contemplacao] => 2019-11-12 00:00:00 [cep] => 38407526 [codFormaPagto] => 3 [codigo_bem] => 9075 [codPlanoCota] => 70 [data_cancelamento] => 1970-01-01 00:00:01 [dataProxReuniao] => 2020-01-14 00:00:00 [descSituacaoCobranca] => Normal [faseCobranca] => N000 [numSeq] => 0 [percQuitacao] => 26.5461 [valorQuitacao] => 10505.54 [percTotalPago] => 73.4539 [percTotalPendente] => 0 [situacaoCobranca] => N [garagem] => [created_at] => 2019-12-19 12:55:07 [updated_at] => 2019-12-19 12:55:21 ) [original:protected] => Array ( [id] => 459 [user_id] => 842 [contrato] => 851717 [disponivel] => 1 [grupo] => 06271 [cota] => 871 [valor] => 34163 [conta_conjunta] => [novoSegmento] => [originalSegmento] => 06271 [completo] => [novoUsado] => 1 [pessoa] => F [descricao] => 50% COBALT 1.8 (COD.9062) [data_entrega] => 1970-01-01 00:00:01 [data_contemplacao] => 2019-11-12 00:00:00 [cep] => 38407526 [codFormaPagto] => 3 [codigo_bem] => 9075 [codPlanoCota] => 70 [data_cancelamento] => 1970-01-01 00:00:01 [dataProxReuniao] => 2020-01-14 00:00:00 [descSituacaoCobranca] => Normal [faseCobranca] => N000 [numSeq] => 0 [percQuitacao] => 26.5461 [valorQuitacao] => 10505.54 [percTotalPago] => 73.4539 [percTotalPendente] => 0 [situacaoCobranca] => N [garagem] => [created_at] => 2019-12-19 12:55:07 [updated_at] => 2019-12-19 12:55:21 ) [changes:protected] => Array ( ) [casts:protected] => Array ( ) [dates:protected] => Array ( ) [dateFormat:protected] => [appends:protected] => Array ( ) [dispatchesEvents:protected] => Array ( ) [observables:protected] => Array ( ) [relations:protected] => Array ( ) [touches:protected] => Array ( ) [timestamps] => 1 [hidden:protected] => Array ( ) [visible:protected] => Array ( ) [fillable:protected] => Array ( ) ) [1] => Illuminate\Database\Eloquent\Collection Object ( [items:protected] => Array ( [0] => App\Contrato Object ( [guarded:protected] => Array ( ) [connection:protected] => mysql [table:protected] => contratos [primaryKey:protected] => id [keyType:protected] => int [incrementing] => 1 [with:protected] => Array ( ) [withCount:protected] => Array ( ) [perPage:protected] => 15 [exists] => 1 [wasRecentlyCreated] => [attributes:protected] => Array ( [id] => 459 [user_id] => 842 [contrato] => 851717 [disponivel] => 1 [grupo] => 06271 [cota] => 871 [valor] => 34163 [conta_conjunta] => [novoSegmento] => [originalSegmento] => 06271 [completo] => [novoUsado] => 1 [pessoa] => F [descricao] => 50% COBALT 1.8 (COD.9062) [data_entrega] => 1970-01-01 00:00:01 [data_contemplacao] => 2019-11-12 00:00:00 [cep] => 38407526 [codFormaPagto] => 3 [codigo_bem] => 9075 [codPlanoCota] => 70 [data_cancelamento] => 1970-01-01 00:00:01 [dataProxReuniao] => 2020-01-14 00:00:00 [descSituacaoCobranca] => Normal [faseCobranca] => N000 [numSeq] => 0 [percQuitacao] => 26.5461 [valorQuitacao] => 10505.54 [percTotalPago] => 73.4539 [percTotalPendente] => 0 [situacaoCobranca] => N [garagem] => [created_at] => 2019-12-19 12:55:07 [updated_at] => 2019-12-19 12:55:21 ) [original:protected] => Array ( [id] => 459 [user_id] => 842 [contrato] => 851717 [disponivel] => 1 [grupo] => 06271 [cota] => 871 [valor] => 34163 [conta_conjunta] => [novoSegmento] => [originalSegmento] => 06271 [completo] => [novoUsado] => 1 [pessoa] => F [descricao] => 50% COBALT 1.8 (COD.9062) [data_entrega] => 1970-01-01 00:00:01 [data_contemplacao] => 2019-11-12 00:00:00 [cep] => 38407526 [codFormaPagto] => 3 [codigo_bem] => 9075 [codPlanoCota] => 70 [data_cancelamento] => 1970-01-01 00:00:01 [dataProxReuniao] => 2020-01-14 00:00:00 [descSituacaoCobranca] => Normal [faseCobranca] => N000 [numSeq] => 0 [percQuitacao] => 26.5461 [valorQuitacao] => 10505.54 [percTotalPago] => 73.4539 [percTotalPendente] => 0 [situacaoCobranca] => N [garagem] => [created_at] => 2019-12-19 12:55:07 [updated_at] => 2019-12-19 12:55:21 ) [changes:protected] => Array ( ) [casts:protected] => Array ( ) [dates:protected] => Array ( ) [dateFormat:protected] => [appends:protected] => Array ( ) [dispatchesEvents:protected] => Array ( ) [observables:protected] => Array ( ) [relations:protected] => Array ( ) [touches:protected] => Array ( ) [timestamps] => 1 [hidden:protected] => Array ( ) [visible:protected] => Array ( ) [fillable:protected] => Array ( ) ) ) ) [2] => App\Endereco Object ( [connection:protected] => mysql [table:protected] => enderecos [primaryKey:protected] => id [keyType:protected] => int [incrementing] => 1 [with:protected] => Array ( ) [withCount:protected] => Array ( ) [perPage:protected] => 15 [exists] => 1 [wasRecentlyCreated] => [attributes:protected] => Array ( [id] => 395 [user_id] => 842 [logradouro] => R DA REALIZAÇÃO [numero] => 760 [bairro] => JOANA DARC [municipio] => [uf] => MG [complemento] => [telefone] => (34) 9885-1104 [celular] => (11) 91234-5678 [cep] => 38407-526 [correspondencia] => [tempoResidencia] => 10 [created_at] => 2019-12-19 12:55:12 [updated_at] => 2019-12-19 13:03:50 ) [original:protected] => Array ( [id] => 395 [user_id] => 842 [logradouro] => R DA REALIZAÇÃO [numero] => 760 [bairro] => JOANA DARC [municipio] => [uf] => MG [complemento] => [telefone] => (34) 9885-1104 [celular] => (11) 91234-5678 [cep] => 38407-526 [correspondencia] => [tempoResidencia] => 10 [created_at] => 2019-12-19 12:55:12 [updated_at] => 2019-12-19 13:03:50 ) [changes:protected] => Array ( ) [casts:protected] => Array ( ) [dates:protected] => Array ( ) [dateFormat:protected] => [appends:protected] => Array ( ) [dispatchesEvents:protected] => Array ( ) [observables:protected] => Array ( ) [relations:protected] => Array ( ) [touches:protected] => Array ( ) [timestamps] => 1 [hidden:protected] => Array ( ) [visible:protected] => Array ( ) [fillable:protected] => Array ( ) [guarded:protected] => Array ( [0] => * ) ) [3] => App\User Object ( [fillable:protected] => Array ( [0] => name [1] => cpfCnpj [2] => password ) [hidden:protected] => Array ( [0] => password [1] => remember_token ) [casts:protected] => Array ( [email_verified_at] => datetime ) [guarded:protected] => Array ( ) [additional_attributes] => Array ( [0] => locale ) [connection:protected] => mysql [table:protected] => users [primaryKey:protected] => id [keyType:protected] => int [incrementing] => 1 [with:protected] => Array ( ) [withCount:protected] => Array ( ) [perPage:protected] => 15 [exists] => 1 [wasRecentlyCreated] => [attributes:protected] => Array ( [id] => 842 [role_id] => 2 [fiador_id] => [name] => JOSE CARLOS SOARES [email] => email#pwa.com [avatar] => users/default.png [email_verified_at] => [password] => $2y$10$EqgjoWwYe2FBLDkJALqUm.kNLQCjovdEuRrtIhOfEV9lvqM2LxP8G [remember_token] => [settings] => [cc] => [unidade] => [matricula] => [departamento] => [equipe] => [cep] => [cargo] => [uf] => [telefoneComercial] => [celular_comercial] => [telefone] => [nascimento] => [seriePagSeguro] => [senhaMaquininha] => [numeroArmario] => [precisaAssEletronica] => [whatsapp] => [novaAssinatura] => [cpfCnpj] => 00445341670 [IE] => [estado_civil_id] => 1 [renda] => 2 [tipoBeneficio] => [numeroBeneficio] => [tempoBeneficio] => [atividade_principal] => [atividades_secundarias] => [capital_social] => [data_situacao] => [data_situacao_especial] => [fantasia] => [motivo_situacao] => [natureza_juridica] => [porte] => [status] => [tipo] => [ultima_atualizacao] => [receita] => [idERP] => 1 [sms] => [adesao] => [created_at] => 2019-12-19 12:55:07 [updated_at] => 2019-12-19 13:59:20 ) [original:protected] => Array ( [id] => 842 [role_id] => 2 [fiador_id] => [name] => JOSE CARLOS SOARES [email] => email#pwa.com [avatar] => users/default.png [email_verified_at] => [password] => $2y$10$EqgjoWwYe2FBLDkJALqUm.kNLQCjovdEuRrtIhOfEV9lvqM2LxP8G [remember_token] => [settings] => [cc] => [unidade] => [matricula] => [departamento] => [equipe] => [cep] => [cargo] => [uf] => [telefoneComercial] => [celular_comercial] => [telefone] => [nascimento] => [seriePagSeguro] => [senhaMaquininha] => [numeroArmario] => [precisaAssEletronica] => [whatsapp] => [novaAssinatura] => [cpfCnpj] => 00445341670 [IE] => [estado_civil_id] => 1 [renda] => 2 [tipoBeneficio] => [numeroBeneficio] => [tempoBeneficio] => [atividade_principal] => [atividades_secundarias] => [capital_social] => [data_situacao] => [data_situacao_especial] => [fantasia] => [motivo_situacao] => [natureza_juridica] => [porte] => [status] => [tipo] => [ultima_atualizacao] => [receita] => [idERP] => 1 [sms] => [adesao] => [created_at] => 2019-12-19 12:55:07 [updated_at] => 2019-12-19 13:59:20 ) [changes:protected] => Array ( ) [dates:protected] => Array ( ) [dateFormat:protected] => [appends:protected] => Array ( ) [dispatchesEvents:protected] => Array ( ) [observables:protected] => Array ( ) [relations:protected] => Array ( [role] => TCG\Voyager\Models\Role Object ( [guarded:protected] => Array ( ) [connection:protected] => mysql [table:protected] => roles [primaryKey:protected] => id [keyType:protected] => int [incrementing] => 1 [with:protected] => Array ( ) [withCount:protected] => Array ( ) [perPage:protected] => 15 [exists] => 1 [wasRecentlyCreated] => [attributes:protected] => Array ( [id] => 2 [name] => user [display_name] => Normal User [created_at] => 2019-06-10 14:53:44 [updated_at] => 2019-06-10 14:53:44 ) [original:protected] => Array ( [id] => 2 [name] => user [display_name] => Normal User [created_at] => 2019-06-10 14:53:44 [updated_at] => 2019-06-10 14:53:44 ) [changes:protected] => Array ( ) [casts:protected] => Array ( ) [dates:protected] => Array ( ) [dateFormat:protected] => [appends:protected] => Array ( ) [dispatchesEvents:protected] => Array ( ) [observables:protected] => Array ( ) [relations:protected] => Array ( ) [touches:protected] => Array ( ) [timestamps] => 1 [hidden:protected] => Array ( ) [visible:protected] => Array ( ) [fillable:protected] => Array ( ) ) [roles] => Illuminate\Database\Eloquent\Collection Object ( [items:protected] => Array ( ) ) ) [touches:protected] => Array ( ) [timestamps] => 1 [visible:protected] => Array ( ) [rememberTokenName:protected] => remember_token ) ) 1
The error:
Undefined variable: contrato (View: /Users/marcellopato/Sites/primorossi/resources/views/contemplado/notaPromissoria.blade.php)
As you can see, I want to pass those types of data to the PDF. It works well when passing to view, but I can't do the export to PDF.
Any hints?
Thanks in advance!
You are not passing an associative array where the keys are what you want the variables to be named in the view:
PDF::loadView(..., [
'pessoa' => $pessoa,
'contrato' => $contrato,
'endereco' => $endereco,
'consorciado' => $consorciado,
]);
OR using compact:
PDF::loadView(..., compact('pessoa', 'contrato', 'endereco', 'consorciado'));
With what you currently have, even if it was a regular view, you would have to access all the variables from $data: $data[0], $data[1], etc., as they are not named because you have a zero index array, not an associative array. You are passing an array like so:
['data' => [$pessoa, $contrator, ...]]
Solved that issue by exporting the view AFTER passing variables and then applying CSS!
Related
Save arrangement to Livewire
I need to save an array generated when I select several input type checkboxes, and I don't know how to do it Laravel Livewire. So, in this section, I select the checkboxes and send them by wire "documentos." <input wire:model.defer="documentos" name="documentos" type="checkbox" value="Acta" class="focus:ring-indigo-500 h-4 w-4 text-indigo-600 border-gray-300 rounded"> <label for="acta" class="form-check-label">Acta</label> <br></br> <input wire:model.defer="documentos" name="documentos" type="checkbox" value="Documento Ideas" class="focus:ring-indigo-500 h-4 w-4 text-indigo-600 border-gray-300 rounded"> <label for="ideas" class="form-check-label">Documento Ideas</label> <input wire:model.defer="documentos" name="documentos" type="checkbox" value="Plan Inversion" class="focus:ring-indigo-500 h-4 w-4 text-indigo-600 border-gray-300 rounded"> <label for="plan" class="form-check-label">Plan Inversion</label> </div> I have the save function in this section, but it only saves one value. public function guardar() { $data = [ ['id' => $this->use_id], [ 'tarea_paso' => $this->tarea_paso, 'descripcion_paso' => $this->descripcion_paso, 'fecha_inicio' => $this->fecha_inicio, 'fecha_fin' => $this->fecha_fin, 'id_responsable' => $this->id_responsable, 'documentos' => $this->documentos, 'acta' => $this->acta, 'ideas' => $this->ideas, 'plan' => $this->plan, 'acciones' => $this->acciones, 'poais_id' => $this->metodologia_id, ] ]; }
try this $data = [ 'tarea_paso' => $this->tarea_paso, 'descripcion_paso' => $this->descripcion_paso, 'fecha_inicio' => $this->fecha_inicio, 'fecha_fin' => $this->fecha_fin, 'id_responsable' => $this->id_responsable, 'documentos' => $this->documentos, 'acta' => $this->acta, 'ideas' => $this->ideas, 'plan' => $this->plan, 'acciones' => $this->acciones, 'poais_id' => $this->metodologia_id, ]; Model::where('id', $this->use_id)->update($data);
Lavachart - can not set property of "style" of null
I just started using this library in laravel but it seems that it's not working. This is the controller's code used: $entries = \Lava::DataTable(); $query = Survey::select('country AS 0', \DB::raw('count(country) AS entries'))->groupBy('country')->get()->toArray(); $data = []; foreach ($query as $q) { $data[] = [$q[0], $q['entries']]; } $entries->addStringColumn('Country') ->addNumberColumn('Popularity') ->addRows($data); \Lava::GeoChart('Popularity', $entries); return view('dashboard.homepage', ['colorsNum' => $colorsNum]); This is my blade file: <div class="row"> <div class="col-md-12"> <div class="card"> <div class="card-body"> <div id="pop-div"></div> #geochart('Popularity', 'pop-div') </div> </div> </div> </div> enter image description here It's showing this red error: Cannot read property 'style' of null I don't know what's going wrong so please if you can help me, your help is much appreciated.
I resolved the by passing the third parameter options $lava->GeoChart('Popularity', $popularity, [ 'colorAxis' => [ 'minValue' => 0, 'colors' => ['#FF0000', '#00FF00']], //ColorAxis Options 'datalessRegionColor' => '#81d4fa', 'displayMode' => 'auto', 'enableRegionInteractivity' => true, 'keepAspectRatio' => true, 'region' => 'world', 'magnifyingGlass' => ['enable' => true, 'zoomFactor' => 7.5], //MagnifyingGlass Options 'markerOpacity' => 1.0, 'resolution' => 'countries', 'sizeAxis' => null , 'backgroundColor'=> '#81d4fa', ]);
Error while sending data from controller to view in Codeigniter
I am sending data from controller to view in codeigniter, everything works fine until i pass a data that is $this->data['mustvisitedcities']. This is the controller public function index() { $this->data['ptype'] = "index"; if($this->validlang){ $slug = $this->uri->segment(3); }else{ $slug = $this->uri->segment(2); } if (!empty ($slug)) { $this->dests_lib->set_destid($slug); $this->data['details'] = $this->dests_lib->dest_details(); $this->data['title'] = $this->dests_lib->title; $this->data['thumbnail'] = $this->dests_lib->thumbnail; $this->data['date'] = $this->dests_lib->date; $res = $this->Settings_model->get_contact_page_details(); $this->data['phone'] = $res[0]->contact_phone; $this->data['langurl'] = base_url()."destinations/{langid}/".$this->dests_lib->slug; $mustvisitedlocid = $this->data['details'][0]->related_cities; $this->data['mustvisitedcities'] = $this->dests_lib->get_mustvisitedcity($mustvisitedlocid); $this->setMetaData($this->data['details'][0]->location_meta_title,$this->data['details'][0]->location_meta_desc,$this->data['details'][0]->location_meta_keywords); $this->theme->view('modules/destinations/dest_details', $this->data, $this); } else { $this->listing(); } } problem is passing $this->data['mustvisitedcities'] throw some error that i am not able to find. when i remove this then everything works fine. I tried to print this variable and data is there as i want but its just impossible for me to pass this to view. when i print $this->data['mustvisitedcities'], i get following result Array ( [0] => stdClass Object ( [id] => 2642 [location] => Irkutsk [slug] => https://www.happyvoyaging.com/destinations/Irkutsk [thumbnail] => https://www.happyvoyaging.com/uploads/images/locations/thumbs/ ) [1] => stdClass Object ( [id] => 3067 [location] => Krasnojarsk [slug] => https://www.happyvoyaging.com/destinations/Krasnojarsk [thumbnail] => https://www.happyvoyaging.com/uploads/images/locations/thumbs/ ) [2] => stdClass Object ( [id] => 3554 [location] => Saint Petersburg [slug] => https://www.happyvoyaging.com/destinations/Saint Petersburg [thumbnail] => https://www.happyvoyaging.com/uploads/images/locations/thumbs/ ) [3] => stdClass Object ( [id] => 4081 [location] => Murmansk [slug] => https://www.happyvoyaging.com/destinations/Murmansk [thumbnail] => https://www.happyvoyaging.com/uploads/images/locations/thumbs/ ) [4] => stdClass Object ( [id] => 4131 [location] => Moscow [slug] => https://www.happyvoyaging.com/destinations/Moscow [thumbnail] => https://www.happyvoyaging.com/uploads/images/locations/thumbs/ ) ) in view i am fetching above data as <?php foreach($mustvisitedcities as $item){ ?> <div> <div> <a href="<?php echo $item->slug;?>"> <div> <div> <div class="lazyload-wrapper"> <img src="<?php echo $item->thumbnail;?>" alt="<?php echo character_limiter($item->location,30);?>" data-pin-nopin="true"> </div> </div> </div> <div> <h4 color="#121416"><?php echo character_limiter($item->location,30);?></h4> </div> </a> </div> </div> <?php } ?> When i print entire $this->data, i get this Array ( [ptype] => index [details] => Array ( [0] => stdClass Object ( [id] => 9416 [country] => Russia [location] => Russia [location_slug] => [location_desc] => [location_meta_title] => Russia [location_meta_keywords] => [location_meta_desc] => [location_img] => [location_thumb] => 502844_russian.jpg [related_cities] => 2642,3067,3554,4081,4131 [preferred_cities] => [latitude] => 61.5240 [longitude] => 105.3188 [user] => [status] => Yes ) ) [title] => Russia [thumbnail] => https://www.happyvoyaging.com/uploads/images/locations/thumbs/502844_russian.jpg [date] => [phone] => +918860709211 [langurl] => https://www.happyvoyaging.com/destinations/{langid}/Russia [mustvisitedcities] => Array ( [0] => stdClass Object ( [id] => 2642 [location] => Irkutsk [slug] => https://www.happyvoyaging.com/destinations/Irkutsk [thumbnail] => https://www.happyvoyaging.com/uploads/images/locations/thumbs/ ) [1] => stdClass Object ( [id] => 3067 [location] => Krasnojarsk [slug] => https://www.happyvoyaging.com/destinations/Krasnojarsk [thumbnail] => https://www.happyvoyaging.com/uploads/images/locations/thumbs/ ) [2] => stdClass Object ( [id] => 3554 [location] => Saint Petersburg [slug] => https://www.happyvoyaging.com/destinations/Saint Petersburg [thumbnail] => https://www.happyvoyaging.com/uploads/images/locations/thumbs/ ) [3] => stdClass Object ( [id] => 4081 [location] => Murmansk [slug] => https://www.happyvoyaging.com/destinations/Murmansk [thumbnail] => https://www.happyvoyaging.com/uploads/images/locations/thumbs/ ) [4] => stdClass Object ( [id] => 4131 [location] => Moscow [slug] => https://www.happyvoyaging.com/destinations/Moscow [thumbnail] => https://www.happyvoyaging.com/uploads/images/locations/thumbs/ ) ) [pageTitle] => Russia [metadescription] => Book sightseeing tours, attractions, visa and experiences in 500+ destinations at guaranteed low prices with handpicked reliable suppliers. [metakeywords] => Tours, Sightseeing and Things To Do around the World, Russia Visa agent in India, Russia Visa agent Delhi, Dubai Visa agent Delhi, Dubai Visa agent India )
Try using : $data[‘variablename’] = $examplevariable; $data[‘variablename2’] = “This is a test”; $this->load->view(‘phpname’, $data); To call it on view :
Ajax Callback not rebuilding form drupal 8
I have created a form which has two ajax callbacks but neither of them seems to work as expected the form_state do not get rebuild after callback namespace Drupal\dashboard\Form; use Drupal\Core\Form\FormBase; use Drupal\Core\Form\FormStateInterface; use Drupal\user\Entity\User; use Drupal\commerce_price\Price; use Drupal\commerce_order\Entity\OrderItem; use Drupal\commerce_order\Entity\Order; use Drupal\taxonomy\Entity\Term; use Drupal\Core\Ajax\AjaxResponse; use Drupal\Core\Ajax\HtmlCommand; use CommerceGuys\Addressing\AddressFormat\AddressField; use Drupal\dashboard\DashboardRepository; use Symfony\Component\DependencyInjection\ContainerInterface; /** * UI to update a record. * * #ingroup scorecards */ class AcfDataUpdateForm extends FormBase { /** * Our database repository service. * * #var \Drupal\scorecards\ScorecardsRepository */ protected $repository; /** * {#inheritdoc} */ public function getFormId() { return 'acf_data_update_form'; } /** * {#inheritdoc} */ public static function create(ContainerInterface $container) { $form = new static($container->get('dashboard.repository')); $form->setStringTranslation($container->get('string_translation')); $form->setMessenger($container->get('messenger')); return $form; } /** * Construct the new form object. */ public function __construct(DashboardRepository $repository) { $this->repository = $repository; } /** * Sample UI to update a record. */ public function buildForm(array $form, FormStateInterface $form_state, $order_id = NULL) { $items = $this->repository->get_order_items($order_id); $mark_pack = 6; $uid = \Drupal::currentUser()->id(); $config = \Drupal::config('dashboard.settings'); foreach($items as $item){ if($item->purchased_entity == 6 || $item->purchased_entity == 7 || $item->purchased_entity == 8){ $mark_pack = $item->purchased_entity; } } $form['#prefix'] = '<div id="package_design_wrapper-container">'; $form['#suffix'] = '</div>'; $form['order_id'] = array( '#type' => 'hidden', '#default_value' => $order_id, ); $form['package'] = array( '#type' => 'container', '#prefix' => '<div class="message" id="message"></div>', '#attributes' => array('id' => 'marketing-package-wrapper'), ); $form['package']['marketing_package'] = array( '#type' => 'radios', '#default_value' => $mark_pack, '#options' => array( 6 => $this ->t('Standard <span>'.$this->getPrice(6).'</span>'), 7 => $this ->t('Premium <span>'.$this->getPrice(7).'</span>'), 8 => $this ->t('Premium + <span>'.$this->getPrice(8).'</span>'), ), '#disabled' => true, ); $form['package']['designation'] = array( '#type' => 'textfield', '#prefix' => $this->t('<h3>your designation</h3><p>Lorem Ipsum is simply dummy text of the printing and typesetting industry</p>'), '#attributes' => array('placeholder' => 'Type Here'), ); $form['package']['photograph'] = array( '#type' => 'managed_file', '#upload_location' => 'public://acf_profile_photos', '#multiple' => FALSE, '#upload_validators' => [ 'file_validate_is_image' => [], 'file_validate_extensions' => array('png jpg jpeg'), 'file_validate_size' => array(25600000) ], '#required' => true, '#title' => $this->t('<h3>your photograph</h3><p>Lorem Ipsum is simply dummy text of the printing and typesetting industry</p>'), ); $form['package']['date'] = array( '#type' => 'radios', '#default_value' => 1, '#options' => $this->getDates(), '#required' => true, '#prefix' => $this->t('<h3>Award Slot</h3><p>Lorem Ipsum is simply dummy text of the printing and typesetting industry</p>'), '#ajax' => [ 'wrapper' => 'wrapper-dropdown', 'callback' => '::getAwardSlots', 'method' => 'replace', 'effect' => 'fade', 'event' => 'change', 'progress' => [ 'type' => 'throbber', 'message' => NULL, ], ], ); $form['package']['award_slot'] = array( '#type' => 'radios', '#default_value' => 1, '#options' => $form_state->getValue('date') ? $this->getAwardSlotOptions($form_state->getValue('date')) : $this->getAwardSlotOptions('2021-04-21'), '#prefix' => '<div id="wrapper-dropdown">', '#suffix' => '</div>', '#required' => true, ); $form['package']['bio'] = array( '#type' => 'textarea', '#prefix' => $this->t('<h3>Individual Bio</h3><p>Lorem Ipsum is simply dummy text of the printing and typesetting industry</p>'), '#attributes' => array('placeholder' => 'Type Here'), ); $form['package']['plaque_type'] = array( '#type' => 'radios', '#default_value' => 'remote', '#options' => array( 'remote' => $this ->t('remote'), 'event' => $this ->t('event'), ), '#required' => true, '#prefix' => $this->t('<h3>Plaque Type</h3>'), ); $form['package']['shipping_address'] = array( '#type' => 'container', '#states' => array( 'visible' => array( ':input[name="plaque_type"]' => array( 'value' => 'remote', ), ), ), ); $form['package']['shipping_address']['markup'] = array( '#markup' => ' <h3>shipping address</h3><p>Lorem Ipsum is simply dummy text of the printing and typesetting industry</p>', ); $form['package']['shipping_address']['address'] = array( '#type' => 'address', '#default_value' => ['country_code' => 'US'], '#used_fields' => [ AddressField::GIVEN_NAME, AddressField::FAMILY_NAME, AddressField::ORGANIZATION, AddressField::ADDRESS_LINE1, AddressField::ADDRESS_LINE2, AddressField::LOCALITY, AddressField::POSTAL_CODE, ], '#available_countries' => ['US'], '#attributes' => array('class' => array('edit-address')), ); $form['package']['save'] = array( '#type' => 'submit', '#submit' => ['::submitPackageDetails'], '#name' => 'mark-save', '#value' => t('Save'), '#validate' => ['::validatePackageDetails'], '#prefix' => '<div class="row"><div class="col-md-6">', '#suffix' => '</div>', '#ajax' => [ 'wrapper' => 'package_design_wrapper-container', 'progress' => [ 'type' => 'throbber', 'message' => NULL, ], ], ); $form['package']['submit'] = array( '#type' => 'submit', '#submit' => ['::submitPackageDetails'], '#validate' => ['::validatePackageDetails'], '#name' => 'mark-submit', '#value' => t('Submit'), '#prefix' => '<div class="col-md-6">', '#suffix' => '</div></div>', '#ajax' => [ 'wrapper' => 'package_design_wrapper-container', 'progress' => [ 'type' => 'throbber', 'message' => NULL, ], ], ); $form['terms'] = array( '#type' => 'checkbox', '#title' => t('I have read the terms & conditions and agree to comply with them. '), '#prefix' => '<div class="row mb-3"><div class="col-12 col-sm-12 col-md-12 col-lg-12">', '#suffix' => '</div></div>', ); $form['#theme'] = 'acf_data_update_form'; return $form; } /** * {#inheritdoc} */ public function submitForm(array &$form, FormStateInterface $form_state) { echo "<pre>"; print_r($form_state->getValues()); die; $old = $this->repository->save_old_data($old_data, $order_id, $user_id); $this->messenger()->addMessage($this->t('Saved old data #entry (#count row updated)', [ '#count' => $old, '#entry' => print_r($old_data, TRUE), ])); if(!empty($old)){ $count = $this->repository->update_nominee($entry, $order_id, $user_id); $this->messenger()->addMessage($this->t('Updated entry #entry (#count row updated)', [ '#count' => $count, '#entry' => print_r($entry, TRUE), ])); } $form_state->setRedirect('scorecards.scorecard_entry_list'); } public function validatePackageDetails(array &$form, FormStateInterface $form_state){ $fields = array('designation','date','award_slot','plaque_type','bio','photograph'); $add_fields = array('given_name','family_name','organization','address_line1','locality','postal_code'); $valid = true; if($form_state->getValue('plaque_type') == 'remote'){ $add = $form_state->getValue('address'); foreach($add_fields as $field){ if(empty($add[$field])){ $form_state->setErrorByName($add[$field], 'Please enter a valid detail'); } } } foreach($fields as $field){ if(empty($form_state->getValue($field))){ $form_state->setErrorByName($field, 'Please enter a valid detail'); } } } public function submitPackageDetails(array &$form, FormStateInterface $form_state){ $fields = array('designation','date','award_slot','plaque_type','bio','photograph'); $add_fields = array('given_name','family_name','organization','address_line1','locality','postal_code'); if($form_state->getValue('plaque_type') == 'remote'){ $add = $form_state->getValue('address'); } $data = array(); $pid = $form_state->getValue('marketing_package'); foreach($fields as $field){ $data[$field] = $form_state->getValue($field); } $data['status'] = 0; $triggering_element = $form_state->getTriggeringElement(); $button_name = $triggering_element['#name']; if($button_name == 'mark-submit'){ $data['status'] = 1; } $order_id = $form_state->getValue('order_id'); $pid = $form_state->getValue('marketing_package'); $entry = $this->repository->saveAcfDetails($order_id,$pid,$data); $entry_add = $this->repository->saveShippingDetails($order_id,$add); $this->setFilePermanent($form_state->getValue('photograph')); if($entry && $entry_add){ $form_state->setRebuild(TRUE); $this->messenger->addMessage(t('Your data has been saved successfully!')); } else{ $this->messenger->addMessage(t('Your data cannot be Saved')); } } function getPrice($id){ $variation = \Drupal\commerce_product\Entity\ProductVariation::load($id); return str_replace('USD','$',$variation->getPrice()); } function setFilePermanent($image_id){ if(!empty($image_id)) { $file = \Drupal\file\Entity\File::load($image_id[0]); if (isset($file) and is_object($file)) { $file->setPermanent(); // FILE_STATUS_PERMANENT; $file->save(); } } } function getDates(){ $config = $this->config('dashboard.settings'); $start_date = $config->get('conference_start_date'); $no_days = $config->get('no_days'); $dates = array(); for($i = 1; $i <= $no_days; $i++){ $j = $i-1; $date = strtotime("{$j} day", strtotime($start_date)); $new_date = date("d-M-Y", $date); $dates[date("Y-m-d", $date)] = 'DAY '.$i.'<span>('.$new_date.')</span>'; } return $dates; } function getAwardSlots(array &$form, FormStateInterface $form_state){ $form_state->setValue('date', $form_state->getValue('date')); $form_state->setRebuild(TRUE); return $form['package']['award_slot']; } function getAwardSlotOptions($date){ $terms = \Drupal::entityManager()->getStorage('taxonomy_term')->loadByProperties(array('name' => $date)); $term = reset($terms); $award_slots = $term->get('field_award_slot'); $slots = array(); foreach($award_slots as $award_slot){ $slots[$award_slot->value] = $award_slot->value; } return $slots; } } I have also created a template for this form <div class="row"> <div class="col-12 col-sm-12 col-md-9 col-lg-9"> <div class="package_border"> <div class="wellcome_back"> <div class="row"> <div class="col-12 col-sm-12 col-md-12 col-lg-12"> <h3>Awardee Deliverables</h3> </div> </div> </div> <div class="package_header"> <div class="row"> <div class="col-12 col-sm-12 col-md-5 col-lg-5"> <div class="package_header_batch"> <img src="/modules/custom/dashboard/images/package.jpg"> <div> <h2>Marketing package</h2> <p>Lorem Ipsum is simply</p> </div> </div> </div> {% if form.package.marketing_package %} <div class="col-12 col-sm-12 col-md-7 col-lg-7"> {{ form.package.marketing_package }} </div> {% endif %} </div> </div> <div class="designation_content_wrapper"> <div class="designation_content"> {{ form.package|without('marketing_package','plaque_type','shipping_address','submit','save') }} {% if form.package.plaque_type %} <h3>plaque</h3> <p>Lorem Ipsum is simply dummy text of the printing and typesetting industry</p> <div class="row mb-5"> <div class="col-12 col-sm-12 col-md-6 col-lg-6"> <figure class="plaque_figure"> {% set images = getPlaqueBadge() %} <img src="{{ images.plaque }}" width="100%"> </figure> </div> <div class="col-12 col-sm-12 col-md-6 col-lg-6"> <div class="plaque_type_wrapper"> {{ form.package.plaque_type }} </div> </div> </div> {% endif %} {% if form.package.shipping_address %} {{ form.package.shipping_address }} {% endif %} {{ form.package.save }} {{ form.package.submit }} </div> </div> </div> {{ form|without('package') }} </div> <div class="col-12 col-sm-12 col-md-3 col-lg-3"> <aside class="package_aside"> <div class="package_aside_wrapper"> <h5>jump to</h5> <ul class="package_aside_list"> <li> designation </li> <li> photograph </li> <li> award slot </li> <li> individual boi </li> <li> plaque </li> <li> plaque type </li> <li> shipping address </li> </ul> </div> </aside> </div> </div> what is actually happening is that after the ajax callback is executed the the form_state still has user submitted values which it should not. please help if anyone knows what m I doing wrong here.
That's kinda old but maybe can help someone :). First of all - you cannot modify $form_state from within the ajax callback - so the $form_state->setRebuid() will not have an effect. As stated in AJAX form docs you should only return a markup, a renderable array or an AjaxCommand. What you need to do here is to modify the value of the element in the ajax callback, more like this: function getAwardSlots(array &$form, FormStateInterface $form_state){ $date = $form_state->getValue('date') $form['package']['award_slot']['#options'] = $this->getAwardSlotOptions($date); return $form['package']['award_slot']; }
How can I display dynamic key of array in the laravel blade?
My controller like this : public function index(Request $request) { $param = $request->all(); $data = $this->itemDetailRepository->getData($param); return view('item-detail.index', compact('param')) ->withItems(count($data)>0?$data:null); } If I debug $data or in laravel (dd($data)), the result like this : So the array $data is collection and pagination like that If I click in the attributes section, it display like this : #attributes: array:5 [▼ "item_number" => "AB-0001" "total_quantity" => "1000" "location-a" => "500" "location-b" => "500" ] So the array data is there In the view blade laravel like this : <table> <tr> <th>ITEM NUMBER</th> <th>TOTAL QUANTITY</th> <th>LOCATION-A</th> <th>LOCATION-B</th> </tr> #foreach($items as $item) <tr> <td>{{ $item->item_number }}</td> <td>{{ $item->total_quantity }}</td> <td>{{ $item['location-a'] }}</td> <td>{{ $item['location-b'] }}</td> </tr> #endforeach </table> It works. But my key of the array is dynamic. The key can change So the array can change like this : #attributes: array:5 [▼ "item_number" => "AB-0001" "total_quantity" => "500" "location-a" => "500" ] Or can change like this : #attributes: array:5 [▼ "item_number" => "AB-0001" "total_quantity" => "1500" "location-a" => "500" "location-b" => "500" "location-c" => "500" ] So the location is dynamic How do I set it in the laravel view blade so that it can adjust to dynamic arrays? Update If I echo '<pre>';print_r($data);'</pre>';die();, the result like this : Illuminate\Pagination\LengthAwarePaginator Object ( [total:protected] => 2428 [lastPage:protected] => 1214 [items:protected] => Illuminate\Database\Eloquent\Collection Object ( [items:protected] => Array ( [0] => App\Models\ItemDetail Object ( [table:protected] => items_details [fillable:protected] => Array ( [0] => item_number [1] => quantity ... ) [connection:protected] => mysql [primaryKey:protected] => id [keyType:protected] => int [incrementing] => 1 [with:protected] => Array ( ) [withCount:protected] => Array ( ) [perPage:protected] => 15 [exists] => 1 [wasRecentlyCreated] => [attributes:protected] => Array ( [item_number] => AB-0001 [total_quantity] => 1000 [location-a] => 500 [location-b] => 500 ) [original:protected] => Array ( [item_number] => AB-0001 [total_quantity] => 1000 [location-a] => 500 [location-b] => 500 ) [changes:protected] => Array ( ) [casts:protected] => Array ( ) [dates:protected] => Array ( ) [dateFormat:protected] => [appends:protected] => Array ( ) [dispatchesEvents:protected] => Array ( ) [observables:protected] => Array ( ) [relations:protected] => Array ( ) [touches:protected] => Array ( ) [timestamps] => 1 [hidden:protected] => Array ( ) [visible:protected] => Array ( ) [guarded:protected] => Array ( [0] => * ) ) [1] => App\Models\ItemDetail Object ( [table:protected] => items_details [fillable:protected] => Array ( [0] => item_number [1] => quantity ... ) [connection:protected] => mysql [primaryKey:protected] => id [keyType:protected] => int [incrementing] => 1 [with:protected] => Array ( ) [withCount:protected] => Array ( ) [perPage:protected] => 15 [exists] => 1 [wasRecentlyCreated] => [attributes:protected] => Array ( [item_number] => AB-0002 [total_quantity] => 1500 [location-a] => 1000 [location-b] => 500 ) [original:protected] => Array ( [item_number] => AB-0002 [total_quantity] => 1500 [location-a] => 1000 [location-b] => 500 ) [changes:protected] => Array ( ) [casts:protected] => Array ( ) [dates:protected] => Array ( ) [dateFormat:protected] => [appends:protected] => Array ( ) [dispatchesEvents:protected] => Array ( ) [observables:protected] => Array ( ) [relations:protected] => Array ( ) [touches:protected] => Array ( ) [timestamps] => 1 [hidden:protected] => Array ( ) [visible:protected] => Array ( ) [guarded:protected] => Array ( [0] => * ) ) ) ) [perPage:protected] => 2 [currentPage:protected] => 1 [path:protected] => http://my-project.test/admin/item-detail [query:protected] => Array ( ) [fragment:protected] => [pageName:protected] => page )
Try this out: #php $counts = array_map('count', $data); $key = array_flip($counts)[max($counts)]; #endphp <table> <tr> #foreach ($data[$key] as $key => $value) <th>{{$key}}</th> #endforeach </tr> #foreach($data as $value) <tr> #foreach ($value as $key => $value) <td>{{$value}}</td> #endforeach </tr> #endforeach </table>
your question is quite confusing, if key is dynamic, you can also send an array with of "key" and can send an array with keys like this //In your controller $values = array( array('item_number' => 'AB-0001','total_quantity' => '500', 'location-a' => '500'), array('item_number' => 'AB-0002','total_quantity' => '5000', 'location-a' => '5000'), array('item_number' => 'AB-0003','total_quantity' => '2000', 'location-a' => '2000'), ); $data = [ 'keys' => ['item_number', 'total_quantity', 'location_a'], 'values' => $values ]; return view('some_blade', $data); In your blade you can access like this #foreach($values as $value) <tr> #foreach($keys as $k) <td>{{ $value[$k]; }}</td> #endforeach </tr> #endforeach hope that helps.