I have more function where I need to read $data['getContacts'] more times, the code working correctly, but there is a clean and different method for call it?
thanks!
class AppController extends CI_Controller {
public $id;
function __construct() {
parent::__construct();
$this->id = !empty($this->input->post('id')) ? (int)$this->input->post('id', TRUE) : '';
}
public function restoreCredit()
{
$data['getContacts'] = $this->appmodel->getContacts($this->id); //repeat here?
if($data['getContacts']->status != false) :
$this->appmodel->restoreCredit($this->id);
endif;
}
public function createRandToken()
{
$data['getContacts'] = $this->appmodel->getContacts($this->id); //repeat here?
if(!empty($data['getContacts']) && $data['getContacts']->token == false):
$this->appmodel->setRandUserToken($this->id);
endif;
}
}
Your could define a function getContacts. It will fetch $contacts first time from the DB, after that it will always returned the fetched Contacts.
<?php
class AppController extends CI_Controller
{
public $id;
public $contacts;
function __construct()
{
parent::__construct();
$this->id = !empty($this->input->post('id')) ? (int) $this->input->post('id', TRUE) : '';
}
public function getContacts() {
if( !empty ( $this->contacts) ) { //If its populated return from here.
return $this->contacts;
}
$this->contacts = $this->appmodel->getContacts($this->id);
return $this->contacts;
}
public function restoreCredit()
{
$data['getContacts'] = $this->getContacts();
if ($data['getContacts']->status != false) :
$this->appmodel->restoreCredit($this->id);
endif;
}
public function createRandToken()
{
$data['getContacts'] = $this->getContacts();
if (!empty($data['getContacts']) && $data['getContacts']->token == false) :
$this->appmodel->setRandUserToken($this->id);
endif;
}
}
Related
I'm working on a website where people can download wallpapers.
I have a table 'Images' with a 'Download' column.
I would like to increment the value on this field for each time people click on the 'download button'
I'm usingg Symphony 6 with EasyAdmin-bundle & Twig
Can someone help me to make a query to increment this value ?
Thank you
enter image description here
<?php
namespace App\Entity;
use App\Repository\ImagesRepository;
use Doctrine\ORM\Mapping as ORM;
#[ORM\Entity(repositoryClass: ImagesRepository::class)]
class Images
{
#[ORM\Id]
#[ORM\GeneratedValue]
#[ORM\Column]
private ?int $id = null;
#[ORM\Column(length: 255)]
private ?string $name = null;
#[ORM\Column(length: 255)]
private ?string $image = null;
#[ORM\Column(nullable: true)]
private ?int $downloads = null;
#[ORM\ManyToOne(inversedBy: 'images')]
private ?Wallpapers $wallpaper = null;
#[ORM\ManyToOne(inversedBy: 'device')]
private ?Devices $devices = null;
public function getId(): ?int
{
return $this->id;
}
public function getName(): ?string
{
return $this->name;
}
public function setName(string $name): self
{
$this->name = $name;
return $this;
}
public function getImage(): ?string
{
return $this->image;
}
public function setImage(string $image): self
{
$this->image = $image;
return $this;
}
public function getDownloads(): ?int
{
return $this->downloads;
}
public function setDownloads(?int $downloads): self
{
$this->downloads = $downloads;
return $this;
}
public function getWallpaper(): ?Wallpapers
{
return $this->wallpaper;
}
public function setWallpaper(?Wallpapers $wallpaper): self
{
$this->wallpaper = $wallpaper;
return $this;
}
public function getDevices(): ?Devices
{
return $this->devices;
}
public function setDevices(?Devices $devices): self
{
$this->devices = $devices;
return $this;
}
public function __toString(): string
{
return $this->image;
}
}
<div class="row">
{% for item in wallpapers.getImages() %}
<div class="col">
<img src="/uploads/wps/{{ item.image }}" class="card"/>
<button>Download</button>
</div>
{% endfor %}
</div>
I tried many example but as it's my first experience with Symphony is a bit complicated to understand all the concept of Query Builder
You must create a new controller with route like this:
#[Route('/downloads/{entity}', name:'downloads')
public function downloads(
Entity $entity,
EntityManagerInterface $em
){
$entity->setDownload($entity->getDownload() + 1);
$em->persist($entity);
$em->flush();
return $this->file($entity->getImage(), 'name_file.ext');
}
in your twig file you can redirect to this func with entity id param.
Function is an example you must use your entity class and get file content to download something.
I am trying to do CRUD operation using Kendo UI to show my data in a grid view.
I can read the data from my database with the following code in my controller (my tables are in SQL Server and connected through a connection string):
[Area("Admin")]
public class HeaderMenuController : Controller
{
private readonly IUnitOfWork _unitOfWork;
public HeaderMenuController(IUnitOfWork unitOfWork)
{
_unitOfWork = unitOfWork;
}
public IActionResult Index()
{
return View();
}
public DataSourceResult Products_Read([DataSourceRequest] DataSourceRequest request)
{
return _unitOfWork.HeaderMenu.GetAll().ToDataSourceResult(request);
}
}
index.cshtml
#(Html.Kendo().Grid<MSDACE.Models.HeaderViewModel>()
.Name("grid")
.Columns(columns =>
{
columns.Bound(product => product.HeaderMenuID).Width(100);
columns.Bound(product => product.HeaderMenuName);
columns.Bound(product => product.HeaderMenuDispOrder).Width(250);
columns.Command(commands =>
{
commands.Destroy(); // The "destroy" command removes data items.
}).Title("Commands").Width(200);
})
.ToolBar(toolbar =>
{
toolbar.Create(); // The "create" command adds new data items.
toolbar.Save(); // The "save" command saves the changed data items.
})
.Editable(editable => editable.Mode(GridEditMode.InCell)) // Use in-cell editing mode.
.DataSource(dataSource =>
dataSource.Ajax()
.Batch(true) // Enable batch updates.
.Model(model =>
{
model.Id(product => product.HeaderMenuID); // Specify the property which is the unique identifier of the model.
model.Field(product => product.HeaderMenuID).Editable(false); // Make the ProductID property not editable.
})
.Create(create => create.Action("Products_Create", "HeaderMenu")) // Action method invoked when the user saves a new data item.
.Read(read => read.Action("Products_Read", "HeaderMenu")) // Action method invoked when the Grid needs data.
.Update(update => update.Action("Products_Update", "HeaderMenu")) // Action method invoked when the user saves an updated data item.
.Destroy(destroy => destroy.Action("Products_Destroy", "HeaderMenu")) // Action method invoked when the user removes a data item.
)
.Pageable()
)
The problem is I can't the delete or create operations.
I have written the GetAll, Remove, Get and other functions, but my problem is to reflect in the Kendo Grid
IUnitOfWork.cs
public interface IUnitOfWork : IDisposable
{
IHeaderMenuRepository HeaderMenu { get; }
void Save();
}
IHeaderMenuRepository.cs
public class HeaderMenuRepository : Repository<HeaderMenu>, IHeaderMenuRepository
{
private readonly ApplicationDbContext _db;
public HeaderMenuRepository(ApplicationDbContext db) : base(db)
{
_db = db;
}
public IEnumerable<SelectListItem> GetHeaderMenuList()
{
return _db.HeaderMenu.Select(i => new SelectListItem()
{
Text = i.HeaderMenuName,
Value = i.HeaderMenuID.ToString()
});
}
public void Update(HeaderMenu headerMenu)
{
var objFrobDb = _db.HeaderMenu.FirstOrDefault(s => s.HeaderMenuID == headerMenu.HeaderMenuID);
objFrobDb.HeaderMenuName = headerMenu.HeaderMenuName;
objFrobDb.HeaderMenuDesc = headerMenu.HeaderMenuDesc;
objFrobDb.HeaderMenuActive = headerMenu.HeaderMenuActive;
objFrobDb.HeaderMenuDispOrder = headerMenu.HeaderMenuDispOrder;
_db.SaveChanges();
}
IRepository
public interface IRepository<T> where T : class
{
T Get(int id);
IEnumerable<T> GetAll(
Expression<Func<T, bool>> filter = null,
Func<IQueryable<T>, IOrderedQueryable<T>> orderBy = null,
string includeProperties = null
);
T GetFirstOrDefault(
Expression<Func<T, bool>> filter = null,
string includeProperties = null
);
void Add(T entity);
void Remove(int id);
void Remove(T entity);
}
UnitOfWork.cs
public class UnitOfWork : IUnitOfWork
{
private readonly ApplicationDbContext _db;
public UnitOfWork(ApplicationDbContext db)
{
_db = db;
HeaderMenu = new HeaderMenuRepository(_db);
}
public IHeaderMenuRepository HeaderMenu { get; private set; }
public void Dispose()
{
_db.Dispose();
}
public void Save()
{
_db.SaveChanges();
}
}
Repository.cs
public class Repository<T> : IRepository<T> where T : class
{
protected readonly DbContext Context;
internal DbSet<T> dbSet;
public Repository(DbContext context)
{
Context = context;
this.dbSet = context.Set<T>();
}
public void Add(T entity)
{
dbSet.Add(entity);
}
public T Get(int id)
{
return dbSet.Find(id);
}
public IEnumerable<T> GetAll(Expression<Func<T, bool>> filter = null, Func<IQueryable<T>, IOrderedQueryable<T>> orderBy = null, string includeProperties = null)
{
IQueryable<T> query = dbSet;
if (filter != null)
{
query = query.Where(filter);
}
//include properties will be comma seperated
if (includeProperties != null)
{
foreach (var includeProperty in includeProperties.Split(new char[] { ',' }, StringSplitOptions.RemoveEmptyEntries))
{
query = query.Include(includeProperty);
}
}
if (orderBy != null)
{
return orderBy(query).ToList();
}
return query.ToList();
}
public T GetFirstOrDefault(Expression<Func<T, bool>> filter = null, string includeProperties = null)
{
IQueryable<T> query = dbSet;
if (filter != null)
{
query = query.Where(filter);
}
//include properties will be comma seperated
if (includeProperties != null)
{
foreach (var includeProperty in includeProperties.Split(new char[] { ',' }, StringSplitOptions.RemoveEmptyEntries))
{
query = query.Include(includeProperty);
}
}
return query.FirstOrDefault();
}
public void Remove(int id)
{
T entityToRemove = dbSet.Find(id);
Remove(entityToRemove);
}
public void Remove(T entity)
{
dbSet.Remove(entity);
}
}
HeaderMenuRepository.cs
public class HeaderMenuRepository : Repository<HeaderMenu>, IHeaderMenuRepository
{
private readonly ApplicationDbContext _db;
public HeaderMenuRepository(ApplicationDbContext db) : base(db)
{
_db = db;
}
public IEnumerable<SelectListItem> GetHeaderMenuList()
{
return _db.HeaderMenu.Select(i => new SelectListItem()
{
Text = i.HeaderMenuName,
Value = i.HeaderMenuID.ToString()
});
}
public void Update(HeaderMenu headerMenu)
{
var objFrobDb = _db.HeaderMenu.FirstOrDefault(s => s.HeaderMenuID == headerMenu.HeaderMenuID);
objFrobDb.HeaderMenuName = headerMenu.HeaderMenuName;
objFrobDb.HeaderMenuDesc = headerMenu.HeaderMenuDesc;
objFrobDb.HeaderMenuActive = headerMenu.HeaderMenuActive;
objFrobDb.HeaderMenuDispOrder = headerMenu.HeaderMenuDispOrder;
_db.SaveChanges();
}
}
ApplicationDbContext.cs
public class ApplicationDbContext : IdentityDbContext<IdentityUser>
{
public ApplicationDbContext(DbContextOptions<ApplicationDbContext> options)
: base(options)
{
}
protected override void OnModelCreating(ModelBuilder builder)
{
base.OnModelCreating(builder);
// Customize the ASP.NET Identity model and override the defaults if needed.
// For example, you can rename the ASP.NET Identity table names and more.
// Add your customizations after calling base.OnModelCreating(builder);
}
public DbSet<HeaderMenu> HeaderMenu { get; set; }
}
The problem is I cant to the Delete, Create or Edit operation!
I Belive that I can not make the connection between the Kendo and my Database and have to implement something in my controller.
I try the Kendo.MVC examples but the problem are the northwind and sqllite the used!
Could please help me by this issue to implement the CRUD on Grid using the data in my sqlserver tables.
I am having issue with the route and controller.
The error code consist of sql column not found which is looking for column id from items table. Which im quite curious due to the differences with my migration.
CartController.php
namespace App\Http\Controllers;
use App\Cart;
use App\CartItem;
use Illuminate\Support\Facades\Auth;
use Illuminate\Http\Request;
use App\Http\Requests;
use App\Http\Controllers\Controller;
class CartController extends Controller
{
public function __construct()
{
$this->middleware('auth');
}
public function addItem ($itemNo){
$cart = Cart::where('user_id',Auth::user()->id)->first();
if(!$cart){
$cart = new Cart();
$cart->user_id=Auth::user()->id;
$cart->save();
}
$cartItem = new Cartitem();
$cartItem->itemNo=$itemNo;
$cartItem->cart_id= $cart->id;
$cartItem->save();
return redirect('/cart');
}
public function showCart(){
$cart = Cart::where('user_id',Auth::user()->id)->first();
if(!$cart){
$cart = new Cart();
$cart->user_id=Auth::user()->id;
$cart->save();
}
$items = $cart->cartItems;
$total=0;
foreach($items as $item){
$total+=$item->product->price;
}
return view('cart.view',['items'=>$items,'total'=>$total]);
}
public function removeItem($id){
CartItem::destroy($id);
return redirect('/cart');
}
}
ItemController.php
<?php
namespace App\Http\Controllers;
use App\Item;
use App\Http\Requests;
use App\Http\Controllers\Controller;
use Request;
use Illuminate\Support\Facades\Storage;
use Illuminate\Support\Facades\File;
class ItemController extends Controller
{
public function index(){
$items = item::all();
return view('admin.items',['items' => $items]);
}
public function destroy($itemNo){
item::destroy($itemNo);
return redirect('/admin/items');
}
public function newItem(){
return view('admin.new');
}
public function add() {
$file = Request::file('file');
$extension = $file->getClientOriginalExtension();
Storage::disk('local')->put($file->getFilename().'.'.$extension, File::get($file));
$entry = new \App\File();
$entry->mime = $file->getClientMimeType();
$entry->original_filename = $file->getClientOriginalName();
$entry->filename = $file->getFilename().'.'.$extension;
$entry->save();
$Item = new Item();
$Item->file_id=$entry->id;
$Item->itemName =Request::input('name');
$Item->itemDescription =Request::input('description');
$Item->price =Request::input('price');
$Item->imageurl =Request::input('imageurl');
$Item->save();
return redirect('admin/items');
}
}
I am using Cakephp 2.3.0, loading following component.
class BreadCrumbsComponent extends Component {
public $components = array();
public $controller = null;
public function initialize($controller) {
}
public function startup($controller) {
$this->controller = $controller;
}
public function beforeRender($controller) {
}
public function shutDown($controller) {
}
public function beforeRedirect($controller, $url, $status = null, $exit = true) {
}
public function handle($controllerName = NULL, $actionName = NULL) {
pr($this->controller->modelClass);
}
}
It get error following error
Trying to get property of non-object [APP\Controller\Component\BreadCrumbsComponent.php, line 38]
I am unable to access $this->controller there. Any reason? How do I make it work?
Read here startup method is called after the controller so need to initialize controller in initialize method as below,
public function initialize(&$controller, $settings = array()) {
$this->controller = $controller;
}
Is there a way to set flash message or error message from the Model, in the beforeSave function and read the error/message in the view. And I'm not talking about validation errors.
Something along these lines should work with the information available on hand:
<?php
class AppModel extends Model {
public $lastErrorMessage;
public function beforeSave(...) {
$this->lastErrorMessage = null;
return true;
}
}
<?php
class MyModel Extends AppModel {
public function beforeSave(...) {
parent::beforeSave(..);
if (error) {
$this->lastErrorMessage = 'Some error message';
return false;
}
return true;
}
}
<?php
class MyController extends AppController {
public function action() {
if ($this->MyModel->save($this->request->data)) {
} else {
$message = "Some default message";
if ($this->MyModel->lastErrorMessage) {
$message = $this->MyModel->lastErrorMessage;
}
$this->Session->setFlash($message);
}
}
}