I am using laravel 5.4 and Bootstrap Treeview.
I have enabled the node text as link:
$('#treeview').treeview({data: data, enableLinks: true});
and in the href field of each node in the Json array I have the laravel route
"{{ route('opciones.create') }}"
Here is where I create the tree (I encode this to Json format in another part of my code)
function buildTree(array $elements, $parentId) {
$branch = array();
foreach ($elements as $element) {
$element['text'] = $element['descripcion'];
$element['href'] = "{{ route('opciones.create') }}";
if ($element['padre'] == $parentId){
$nodes = buildTree($elements, $element['id']);
if ($nodes) {
$element['nodes'] = $nodes;
}
$branch[] = $element;
}
}
return $branch;
}
This is the function in the controller that I need to call which returns a view (a blade file)
public function create()
{ $opcionespadre = Opcion::where('tipo', '=', 'SUBMENU')->get();
return view($this->path.'.create', compact('opcionespadre'));
}
I am using this especific function just to test the tree nodes links, I have other functions in the controller where I need to send a parameter, but first I need to make the link goes somewhere.
When I click on the text of the node, it says that the page I am looking for doesn't exist.
This is what appears in the browser bar:
http://127.0.0.1:8000/{{route('opciones.create')}}
What should I do?
The problem is in this line :
$element['href'] = "{{ route('opciones.create') }}";
Do it like this :
function buildTree(array $elements, $parentId) {
$branch = array();
foreach ($elements as $element) {
$element['text'] = $element['descripcion'];
$element['href'] = route('opciones.create');
if ($element['padre'] == $parentId){
$nodes = buildTree($elements, $element['id']);
if ($nodes) {
$element['nodes'] = $nodes;
}
$branch[] = $element;
}
}
return $branch;
}
Related
Im got error in section elseif, i want make HOD looking only at its own department data
public function index(User $user)
{
if(auth()->user()->role == 'Admin')
{
$form = Form::all();
}
elseif(auth()->user()->positions == 'HOD')
{
$form = Form::all()->department('user_id', \Auth::user()->id)->get();
}
else
{
$form = Form::where('user_id', \Auth::user()->id)->get();
}
return view('form.index', ['list_form' => $form]);
}
what should i change in elseif code ?
Try to do a dd() on auth()->user()->positions if it returns nothing, the relation between User model and Positions doesnt exist, or is set up wrong.
I am working in Codeigniter and I want to hide ID from URL.
my current URL is:
www.localhost/CI/services/1/ac_repair
but need this type of URL in codeigniter:
www.localhost/CI/services/ac_repair
View Page Code:
<?=anchor('services/' . $ser->s_id . '/' . url_title($ser->s_title,'_') ,'View Service');?>
Controller Code:
public function services()
{
$this->load->model('ServicesModel', 'ser_model');
$s_id = $this->uri->segment(2, 0);
if($s_id){
$get_service = $this->ser_model->get_ser($s_id);
return $this->load->view('public/detail', compact('get_service') );
}
else
{
// $services = $this->articles->articles_list( $config['per_page'], $this->uri->segment(3) );
$get_services['result'] = $this->ser_model->all_services_list();
// $this->load->view('public/services', ['services'=>$services]);
$this->load->view('public/services', $get_services);
}
}
Model Code here:
public function get_ser($id)
{
// $q = $this->db
$q = $this->db->select('*')
->from('services')
->where( ['s_id' => $id] )
->get();
if ( $q->num_rows() )
return $q->row();
return false;
}
but need this type of URL in codeigniter:
www.localhost/CI/services/ac_repair
If you want this functionality you have to be able to use your title ac_repair in place of the id. This means the title needs to be marked as unique and therefore not contain any duplicates.
The following pseudo-code should give you an idea:
function services($url_title = null) {
if (!is_null($url_title)) {
// get ser would use title instead of $id
$this->db->where('title', $url_title);
} else {
// all rows
}
}
Other methods would be "hacky" and I cannot think of any off the top of my head that I would consider usable.
Side note: you should never be returning in a view
I am using symfony and twig and trying to route to a controller function that exists, using ajax. The route I am trying to get to seems to be appended to the current route (page) that is calling the ajax. What is causing this and what am I doing wrong? I am intermediate at this. Thanks in advance for your efforts.
The ajax looks like;
$.ajax({url: "{{ path('material-stock_check') }}/" + quoteRing.materialId + "/" + quoteRing.gaugeId + "/" + decimal, success: function (results) {
if (results.length === 0) {
quoteRing.findStripWidthAlternates();
}
}});
and the controller looks like
/**
* Check if the strip width is in the Inventory
* #Route("/check/{materialId}/{gaugeId}/{decimal}", defaults={"materialId" = 0, "gaugeId" = 0, "decimal" = 0}, name="material-stock_check")
* #Method("GET")
*/
public function checkStripWidthAction (Request $request, $materialId, $gaugeId, $decimal)
{
$em = $this->getDoctrine()->getManager();
$materialStocks = $em->getRepository('UniflyteBundle:MaterialStock')->findAllByParams(['widthDecimal' => $decimal, 'materialId' => $materialId, 'gaugeId' => $gaugeId]);
if ($request->isXmlHttpRequest()) {
if (null === $materialStocks) {
return new JsonResponse('failure');
}
$results = [];
foreach ($materialStocks as $result) {
$results[] = [
'gaugeId' => $result->getGauge()->getId(),
'materialId' => $result->getMaterial()->getId()
];
}
return new JsonResponse($results);
}
}
When the ajax is called I am getting
No route found for "GET /uniflyte/quote-ring/new/%7B%7B%20path('material-stock_check')%20%7D%7D/93/347/3.45" (from "http://localhost:8088/uniflyte/quote-ring/new/rolled-ring")
The ajax route looks appended to the existing route. What am I doing wrong?
It seems {{ path(...) }} is not being evaluated by twig as #Omar Alves told.
try this, declare a variable in your twig file
<script>
var url = '{{ path("material-stock_check") }}';
</script>
and then use it
Have you declare the path in route file
I have code like this in the base controller:
$this->eu_cookie_preference = $this->input->cookie('eu-cookie-preference');
and in each one of my controller functions I pass this variable to the twig like this:
$this->twig->display('account/my_details.twig', array(
'title' => 'Website | My Details',
'lang' => $this->lang,
'eu_cookie_preference' => $this->eu_cookie_preference,
));
And in the Base Twig I use this variable to do various things.
Is there a way to access the $this->eu_cookie_preference variable from Twig without having to explicitly pass it to each Twig in every controller function?
I have a similar problem with session vars as I have to pass them to each twig in order to access them.
Answer
You can use Twigs addGlobal function to do so. See manual
// Add static text
$twig->addGlobal('text', 'Hello World');
// Add array
$twig->addGlobal('arr', array(1, 2, 3));
// Add objects
$twig->addGlobal('obj', $obj);
You can use these globals just like normal vars:
This is a Text: "{{ text }}",
item in an array {{ arr[0] }},
obj value {{ obj.publicAttr }} or
obj function {{ obj.toHTML5('<img src="" />') }}
Additional information
This way you can implement lazy loading as well. If you load sessions data from your database, that will not be used in every template it can be useful to build a class like this:
class OnDemand {
private $cache;
private $function;
function __construct($function) {
$this->function = $function;
}
private function cache() {
if($this->cache == null) {
$function = $this->function;
$this->cache = $function();
}
}
function __toString() {
$this->cache();
return (string) $this->cache;
}
function __get($key) {
$this->cache();
return $this->cache[$key];
}
function __isset($key) {
$this->cache();
return isset($this->cache[$key]);
}
}
and pass values like this:
$twig->addGlobal('aDataArray', new OnDemand(function(){
// load database data
$data = DB::loadData(...);
return $data;
}));
The function will only be called, when you call the variable in twig.
{{ aDataArray.user.name }}
I created a "callback" function to check if the username exists in the DB.
I have multiple rules for the "username" field, but the only thing that work is my callback function. It refuses to check against the other rules. I tried leaving the field empty, and the "required" rule never kicked in.
Controller:
account.php
function register() {
$this->load->library('validation');
$fields['username'] = "trim|required|callback_username_check";
etc ...
etc ...
$this->validation->set_rules($fields);
if ($this->validation->run()) {
$records = array();
$records['username'] = $this->validation->username;
etc ...
etc ...
$data = $this->account_model->registerNewAccount($records);
}
$this->load->view('register_view');
}
function username_check($username) {
$m = new Mongo();
$collection = $m->selectDB( DBNAME )->selectCollection( TABLE );
$data = $collection->count(array("username" => $username) );
if($data == 1) {
$this->validation->set_message('username_check', '%s is already taken!');
return false;
} else {
return true;
}
}
Try using the new form_validation class here:
http://ellislab.com/codeigniter/user_guide/libraries/form_validation.html
I believe there was a bug about it.