I have 3 tables in database named tbl_product_manager, tbl_tags, tbl_categories. tbl_product_manager and tbl_categories are linked to one to one relations and tbl_tags and tbl_product_manager is linked with many to many relations with pivot table tbl_product_tag. I had used eloquent for this. I am able to perform insert and update operation in those tables but I am stuck in viewing data through HTML.
This is my controller code for view:
public function getProducts()
{
$productList = ProductManagementModel::getAllProducts();
//var_dump($productList); die();
$i = 1;
$products = '';
foreach($productList as $product) {
$products .= '<tr class="odd gradeX">';
$products .= '<td>'.$i++.'</td>';
$products .= '<td>'.$product->product_name.'</td>';
$products .= '<td>'.$product->category_name.'</td>';
$products .= '<td>'.$product->product_cost .'</td>';
if($product->is_active=='1') {
$products .= '<td>'.'<a href="javascript:void(0)" class="unpublish-selectedproduct" id="'.$product->id.'" >'.
'<span class="label label-success"><i class="icon-ok"></i></span></a>  '.'</td>';
} else {
$products .= '<td>'.'<a href="javascript:void(0)" class="publish-selectedproduct" id="'.$product->id.'" >'.
'<span class="label label-warning"><i class="icon-minus-sign"></i></span></a>  '.'</td>';
}
$products .= '<td>'.$product->updated_at.'</td>';
$products .= '<td>'.
'<i class="icon-pencil"></i> Edit '.
'<a href="javascript:void(0)" class="delete-selectedproduct" id="'.$product->id.'" >'.
'<i class="icon-trash" ></i> Delete</a>'.'</td>';
$products .= '</tr>';
}
return View::make('admin.product_management.list', array('products' => $products));
}
Model of table tbl_product_manager
<?php
use Illuminate\Auth\UserTrait;
use Illuminate\Auth\UserInterface;
use Illuminate\Auth\Reminders\RemindableTrait;
use Illuminate\Auth\Reminders\RemindableInterface;
class ProductManagementModel extends Eloquent implements UserInterface, RemindableInterface {
use UserTrait, RemindableTrait;
protected $table = 'product_manager';
public function categories(){
return $this ->hasOne('CategoriesModel','id');
}
public function tag()
{
return $this->hasMany('TagModel','id');
}
public static function getAllProducts(){
return $product = DB::table('product_manager')
->join('categories', 'product_manager.category_id', '=','categories.id')
->select('product_manager.id', 'categories.id','product_manager.*', 'categories.category_name')
->groupby('product_manager.id')
->get();
}
public function tags() {
return $this->belongsToMany('TagModel', 'product_tag', 'product_id', 'tag_id');
}
}
Model of table tbl_tag
<?php
use Illuminate\Auth\UserTrait;
use Illuminate\Auth\UserInterface;
use Illuminate\Auth\Reminders\RemindableTrait;
use Illuminate\Auth\Reminders\RemindableInterface;
class TagModel extends Eloquent implements UserInterface, RemindableInterface {
use UserTrait, RemindableTrait;
/**
* The database table used by the model.
*
* #var string
*/
protected $table = 'tags';
public function productManagement()
{
return $this->hasMany('productManagementModel');
}
public static function getAlltags()
{
return $tags = DB::table('tags')
->get();
}
public function products() {
return $this->belongsToMany('productManagementModel', 'product_tag', 'tag_id', 'product_id');
}
}
model of pivot table tbl_product_tag
<?php
use Illuminate\Auth\UserTrait;
use Illuminate\Auth\UserInterface;
use Illuminate\Auth\Reminders\RemindableTrait;
use Illuminate\Auth\Reminders\RemindableInterface;
class ProductTagModel extends Eloquent implements UserInterface, RemindableInterface {
use UserTrait, RemindableTrait;
protected $table = 'product_tag';
public $limit;
public static function productTags()
{
return $productTag = DB::table('product_tag')
->get();
}
}
I am making the html view in controller itself. I want to use eloquent for to access the data of tbl_tag which is linked with the pivot table and the parent table(tbl_product_manager) is also linked with the pivot table.
You didn't show how are you trying to display tags. Looks like you just to display all tags for each product. In this case, load the data:
$products = ProductManagementModel::with('tags')->get();
And then display it:
#foreach ($products as $product)
{{ $product->name }}
#foreach ($product->tags as $tag)
{{ $tag->name }}
#endforeach
#endforeach
Related
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
I have a query in existing application now i need to update query in eloquent way i have the following structure of my relationships how can i write the following query in eloquent way
Controller Query that i want to change in eloquent way
foreach ($data['Divisions'] as $sections) {
$SecQry1 = "SELECT sections.id, sections.division_id, sections.code, sections.name ,specifications.description
from specifications inner JOIN sections on specifications.section_id=sections.id where specifications.status='active'
AND specifications.manufacturer_id = $user->id AND sections.division_id=" . $sections->id . " group by sections.id";
$SectionsDivision1 = DB::select($SecQry1);
foreach ($SectionsDivision1 as $key => $selectionDiv) {
array_push($selectionDiv_array1, $selectionDiv);
}
}
class Specification extends Model {
protected $table = 'specifications';
public function section()
{
return $this->belongsTo('App\Section');
}
}
class Section extends Model {
protected $table = 'sections';
public function specifications()
{
return $this->hasMany('App\Specification', 'section_id');
}
public function division()
{
return $this->belongsTo('App\Division');
}
}
class Division extends Model {
protected $table = 'divisions';
protected $fillable = array('name', 'description', 'code','status');
public function sections()
{
return $this->hasMany('App\Section', 'division_id');
}
}
0 => {#1063 ▼
+"id": 1
+"division_id": 1
+"code": "03 01 00"
+"name": "Maintenance of Concrete"
+"description": null
}
]
You dont need relations for this specific query, you could use Laravel Eloquent with join like so:
$SectionsDivision1 = Specification::join('sections', 'specifications.section_id', '=', 'sections.id')
->where([
'specifications.status' => 'active',
'specifications.manufacturer_id' => $user->id,
'sections.division_id' => $sections->id
])->select('sections.id', 'sections.division_id', 'sections.code', 'sections.name', 'specifications.description')
->groupBy('sections.id');
I hope it helps
I have problem with my first module.
I create a module modules/fashion/fashion.php
<?php
class Fashion extends Module
{
function __construct()
{
$this->name = 'fashion';
$this->tab = 'administration';
$this->version = 1.0;
$this->bootstrap = true;
parent::__construct(); // The parent construct is required for translations
$this->page = basename(__FILE__, '.php');
$this->displayName = $this->l('Block Fashion');
$this->description = $this->l('Add a fashion block');
}
public function install()
{
if (!parent::install() ||
!$this->registerHook('header')) {
return false;
}
if (Shop::isFeatureActive()) {
Shop::setContext(Shop::CONTEXT_ALL);
}
$tab = new Tab();
$tab->active = 1;
$tab->class_name = 'AdminFashionController';
$tab->name = array();
foreach (Language::getLanguages(true) as $lang) {
$tab->name[$lang['id_lang']] = "Fashion";
}
$tab->id_parent = (int)Tab::getIdFromClassName('Fashion');
$tab->module = $this->name;
return $tab->add();
}
public function uninstall()
{
// Uninstall Tabs
$tab = new Tab((int)Tab::getIdFromClassName('Fashion'));
$tab->delete();
// Uninstall Module
if (!parent::uninstall())
return false;
}
/**
* Returns module content
*
* #param array $params Parameters
* #return string Content
*/
}
?>
What is more i create modules/fashion/controller/admin/FashionAdminController.php
<?php
class FashionAdminController extends ModuleAdminController
{
public function initContent(){
parent::initContent();
$this->setTemplate('fashion.tpl');
}
}
?>
And modules/fashion/views/templates/admin/fashion.tpl
<!-- Block mymodule -->
<div id="mymodule_block_left" class="block">
<h4>Welcome!</h4>
<div class="block_content">
<p>Hello,
{if isset($my_module_name) && $my_module_name}
{$my_module_name}
{else}
World
{/if}
!
</p>
<ul>
<li>Click me!</li>
</ul>
</div>
</div>
<!-- /Block mymodule -->
So, when i click in my Admin Panel the link Fashion the shows "The page is no found" Why? What i did wrong? Can someone help me?
At first, check if the menu(tab) has been created in the backend or not.
I also think that the admin controller name should start with ADMIN : AdminFashionController and use this name for tab class :
$tab->class_name = 'AdminFashion';
Sample from default module:
public function installTab()
{
$tab = new Tab();
$tab->active = 1;
$tab->class_name = "AdminLinkWidget";
$tab->name = array();
foreach (Language::getLanguages(true) as $lang) {
$tab->name[$lang['id_lang']] = "Link Widget";
}
$tab->id_parent = (int)Tab::getIdFromClassName('AdminParentThemes');
$tab->module = $this->name;
return $tab->add();
}
You have to add "active" and remove "position"(is automatic)
Is there any way to create a view for custom tag in Phalcon so I can just pass the parameters to be rendered?
class MenuModule extends \Phalcon\Tag {
public static function initialize($param) {
return $param;
}
}
In my view I can call
echo MenuModule::initialize('Home Page');
What I want to do is to pass array like:
$menu = array('Home','About','Contact');
echo MenuModule::initialize($menu);
And then in Tag Helper to call a subview to render that array instead of something like this:
class MenuModule extends \Phalcon\Tag {
public static function initialize($param) {
$menu = '<ul>';
foreach($param as $p) {
$menu .= '<li>' . $p . '</li>';
}
$menu .= '</ul>';
return $menu;
}
}
This is not that complex, but I want to use views instead of generating HTML inside PHP because of a larger HTML files.
How can I do this please?
I found solution, Tag Service and Creating your own helpers on official Phalcon documentation.
<?php
use Phalcon\Tag;
class MenuModule extends Tag {
static public function initialize($param) {
$menu = '<ul>';
foreach($param as $p) {
$menu .= '<li>' . $p . '</li>';
}
$menu .= '</ul>';
return $menu;
}
}
Then change the definition of the service ‘tag’:
$di['tag'] = function () {
return new MenuModule();
};
And then in volt access it like:
{{ MenuModule::initialize($param) }}
I have following tables
notice[id, type],
property[id, type],
property_value[id, notice_id, property_id, value].
Each notice has own properties specified by it's type. I need to make a filter by several properties simultaniously, and issue is how to specify which property shoud have a specified value?
class Notice extends CActiveRecord{
/** #var array property_id=>value from $_GET*/
public $searchParams= array();
public function search() {
$criteria = new CDbCriteria;
// $criteria->together = true;
$criteria->compare('t.type', $this->type);
foreach ( $searchParams as $property_id => $value) {
/// What should i write here?
/// $criteria->compare('propertyValues.id', $id);
/// $criteria->compare('propertyValues.value', $value);
}
}
}
Ps: Found this and this but i need specify params...
As i found this issue is around a classic EAV model (Entity–attribute–value). So for temporary (but no finest) solution i join value's table multiply times for every parameter:
public function search() {
foreach ($properties as $id => $value) {
$joinAlias = 'p_' . $property->id;
$join = "\nLEFT JOIN property_value as $joinAlias ON t.id= {$joinAlias}.notice_id AND {$joinAlias}.property_id='{$property_id}' ";
$criteria->compare("{$joinAlias}.value", $value);
$criteria->join .= $join;
}
}