PHPFixing
  • Privacy Policy
  • TOS
  • Ask Question
  • Contact Us
  • Home
  • PHP
  • Programming
  • SQL Injection
  • Web3.0
Showing posts with label components. Show all posts
Showing posts with label components. Show all posts

Wednesday, August 24, 2022

[FIXED] How to change html input value inside a grandchild component from grandparent component

 August 24, 2022     angular, components, input, module, typescript     No comments   

Issue

I have a WidgetsModule where I've created an input component

input.component.ts

import { AfterViewInit, Component, Input, OnInit, Output, ViewChild } from '@angular/core';

@Component({
  selector: 'app-input',
  templateUrl: './input.component.html',
  styleUrls: ['./input.component.css']
})
export class InputComponent implements OnInit, AfterViewInit {
  @Input() Nombre:string = '';
  @Input() Placeholder:string = '';
  @Input() Value:string = '';

  constructor() { }
  ngOnInit(): void { }
  ngAfterViewInit(): void {  this.bindFocusAnimation(); }
  onInput(evt:Event):void{ this.Value = (<HTMLInputElement>evt.target).value; }
  bindFocusAnimation():void{
    var materialInput:HTMLInputElement = <HTMLInputElement>document.getElementById(this.Nombre);
    if(materialInput.value && materialInput.value.trim().length > 0)
      materialInput.parentElement.lastElementChild.setAttribute("class", "label-material active");

    // move label on focus
    materialInput.addEventListener("focus", function () {
      materialInput.parentElement.lastElementChild.setAttribute("class", "label-material active");
    });
    // remove/keep label on blur
    materialInput.addEventListener("blur", function () {
      var css = "label-material";
      if(materialInput.value !== undefined && materialInput.value.trim().length > 0)
        css += " active";
      materialInput.parentElement.lastElementChild.setAttribute("class", css);
    });
  }
}

input.component.html

<div class="input-material-group mb-3">
    <input class="input-material" id="{{Nombre}}" type="text" name="{{Nombre}}" value="{{Value}}" (input)="onInput($event)" autocomplete="off">
    <label class="label-material" for="{{Nombre}}">{{Placeholder}}</label>
</div>

outside the component, I can change the Value's value, but this value is not rendered inside html input. Givin an example, I have a clearFields(); function where I make input.Value = '0', making a console.log() of the component, shows me that the value was correctly changed, but when looking at the html the value is still there

this is the page's code where I render the input component

tipo-componente.component.ts

import { Component, OnInit, ViewChild } from '@angular/core';
import { Constantes } from 'src/app/constantes';
import { ApiRequest } from 'src/app/interface/api-request.interface';
import { TipoComponente } from 'src/app/interface/tipo-componente.interface';
import { TipoComponenteService } from 'src/app/services/tipo-componente.service';
import { WidgetsModule } from 'src/app/widgets/widgets.module';

@Component({
  selector: 'app-tipo-componente',
  templateUrl: './tipo-componente.component.html',
  styleUrls: ['./tipo-componente.component.css']
})
export class TipoComponenteComponent implements OnInit {
  tiposComponentes:TipoComponente[];
  id:number;
  tipo:string;
  icono:string;
  constructor(private TipoComponenteSvc:TipoComponenteService) { }

  ngOnInit(): void {
  }
  ngAfterViewInit() {
    this.cargarTiposComponentes();
    this.limpiarCampos();
  }
  cargarTiposComponentes():void{
    const req:ApiRequest = {  
      Usuario:Constantes.usuario.Usuario,
      Contrasenia:Constantes.usuario.Contrasenia,
      Key:Constantes.usuario.Key,
      RequestObject:{ Id:0, Descrip:'' }
    };

    // this.TipoComponenteSvc.cargar(req).pipe(
    //   tap(
    //     res => {
    //       if(res.Status){
    //         this.tiposComponentes = <TipoComponente[]>res.Data;
    //       }
    //       else
    //         console.log(res.Mensaje);
    //     }
    //   )
    // ).subscribe();
  }
  limpiarCampos():void{
    this.id = 0;
    this.tipo = '0';
    this.icono = '';
  }
  btnNuevo_Click():void{
    this.limpiarCampos();
    WidgetsModule.showPanel('pnlTipoComponente');
  }
  btnGuardar_Click():void{
    WidgetsModule.hidePanel('pnlTipoComponente');
    this.limpiarCampos();
  }
  btnEditar_Click(element:TipoComponente):void{
    WidgetsModule.showPanel('pnlTipoComponente');
  }
  btnEliminar_Click(element:TipoComponente):void{
    WidgetsModule.hidePanel('pnlTipoComponente');
    this.cargarTiposComponentes();
  }
}

tipo-componente.component.html

  <section>
    <div class="container-fluid">
      <div class="row gy-4">
        <div class="col-12">
            <div class="card mb-0">
              <div class="card-header">
                <h3 class="h4 mb-0 title">Compact Table</h3>
                <div class="w-auto tool-box">
                    <a class="tool-button new-button" id="btnNuevo" (click)="btnNuevo_Click()">
                        <svg class="svg-icon svg-icon-sm svg-icon-heavy">
                            <use xlink:href="#add-1"></use>
                        </svg> Nuevo
                    </a>
                </div>
              </div>
              <div class="card-body pt-0">
                <div class="row new-element-panel" id="pnlTipoComponente" style="display:none">
                  <input type="hidden" id="hfId" [value]="id"/>
                  <div class="col-3">
                    <app-input Nombre="inTipo" [Value]="tipo" Placeholder="Tipo de Componente"></app-input>
                  </div>
                  <div class="col-3">
                    <app-input Nombre="inIcono" [Value]="icono" Placeholder="Ícono"></app-input>
                  </div>
                  <div class="">
                    <a class="tool-button save-button" id="btnGuardar" (click)="btnGuardar_Click()">
                        <svg class="svg-icon svg-icon-sm svg-icon-heavy">
                            <use xlink:href="#add-1"></use>
                        </svg> Guardar
                    </a>
                  </div>
                </div>
                <div class="table-responsive">
                  <table class="table mb-0 table-striped table-sm">
                    <thead>
                      <tr>
                        <th>#</th>
                        <th>Descripción</th>
                        <th>Ícono</th>
                      </tr>
                    </thead>
                    <tbody>
                      <tr *ngFor="let tipo of this.tiposComponentes; let index = index">
                        <th>{{ tipo.Id }}</th>
                        <td>{{ tipo.Descrip }}</td>
                        <td>{{ tipo.Icono }}</td>
                      </tr>
                    </tbody>
                  </table>
                </div>
              </div>
            </div>
          </div>
      </div>
    </div>
  </section>

I'v tried using @ViewChild annotations, EventEmitters, and I can't really remember what else (again stuck with this since the last week xD). I look forward for your answers and thanks in advance


Solution

From what I have tested, the problem is that Angular does not bind the variable in the "tipo-componente" component to the variable in the "input" component.

I think the best option you have is using eventEmitter. EventEmitter allows your component to send events. For example:

In your input.component.ts file:

@Output() setInput = new EventEmitter<string>();

onInput(evt:Event) : void {
   this.Value = (<HTMLInputElement>evt.target).value; 
   console.log(this.Value)
   this.setInput.emit(this.Value);
}

This will make your input component send a "setInput" event each time you change the input.

In your tipo-componente.component.html:

<app-input Nombre="inTipo" [Value]="tipo" Placeholder="Tipo de Componente" (setInput)="receiveInput($event)"></app-input>

This will make your app listen to the "setInput" event from app-input and call the receiveInput() method.

In your tipo-componente.component.ts:

receivedInput(event : string){
   this.tipo = event;
}

This will make your app change the value of the variable "tipo" in the "tipo-componente" component.

Fell free to ask for clarification if needed!

EDIT

Please note that the EventEmitter class is the one from @angular/core



Answered By - Manuel Tomás
Answer Checked By - Pedro (PHPFixing Volunteer)
Read More
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg

Wednesday, August 17, 2022

[FIXED] How to pass an array from one component to its sub component

 August 17, 2022     angular, arrays, components, input, output     No comments   

Issue

After googling lots of related answers and tries, I seemly have to seek help here. I have an angular application, one of its components named stock-subscribe, which is used to display the feeTypes that a customer subscribed. Within this component, I created another component, stock-addsubs, used to display the feeTypes that are not yet subscribed by this customer. enter image description here

Obviously, the two feeType lists can compose one whole list. From stock-subscribe, I can get an array, subscribedFeeIds, which holds all the ids of those subscribed feeTypes.

My requirement is to pass this array, subscribedFeeIds, to the stock-addsubs component so that I can filter out those yet unsubscribed feeTypes based on those ids of the array.

To my best understanding, the data passing from one component to its sub component should be a simple process and neither of two component html templates should be involved for my case. Of the many googled solutions, using @Output and @Input seems the simpler than event emitting. However, none can successfully pass the elements of the array in the sub component.

I can get the expected id list (subscribedFeeIds[]) from the stock-subscribe component, and all the rest code work fine so long as the array passed to the sub component is not EMPTY.

1) stock-subscribe.component.ts

    @Component({
      selector: 'app-stock-subscribe',
      templateUrl: './stock-subscribe.component.html',
      styleUrls: ['./stock-subscribe.component.scss']
    })
    export class StockSubscribeComponent implements OnInit {    
      userSubscribe: ISubscribe;    
      @Output() subscribedFeeIds: any = [];  

      listData: MatTableDataSource<any>;

      constructor(private accountService: AccountService,
                  private stockService: StockService) { }

      ngOnInit(): void {
        this.createSubsList();    
      }

      createSubsList() {    
        this.accountService.getUserAccount()
          .subscribe(account => {      
          let userId = account.id.toString();            
          this.stockService.getUserSubscribes(userId).subscribe((data: ISubscribe[]) => {        
            
            // get the id of subscribed fee type and thenpublish to other component
            for (var i = 0; i < data.length; i++)
            {
              if (data[i].status)
                this.subscribedFeeIds.push(data[i].fees[0].id);
            }
            console.log(this.subscribedFeeIds);

            // prepare the list source for display
            this.listData = new MatTableDataSource(data);
            this.listData.sort = this.sort; 
            }, error => {
              console.log(error);
          });
        }, error => {
          console.log(error);
        });    
      }
    }

2) stock-addsubs.component.ts

    @Component({
      selector: 'app-stock-addsubs',
      templateUrl: './stock-addsubs.component.html',
      styleUrls: ['./stock-addsubs.component.scss']
    })
    export class StockAddsubsComponent implements OnInit {
      
      listData: MatTableDataSource<any>; 

      @Input() subscribedFeeIds: any []; 
      
      constructor(private feesService: FeesService) { }

      ngOnInit(): void {
        this.createFeeList();    
      }    

      createFeeList() {                
        this.feesService.getFeeList().subscribe((data: IFee[]) => { 
          
          // filter those already subscribed
          for (var i = 0; i < this.subscribedFeeIds.length; i++)
            {
              for (var j = 0; j < data.length; j++)
              {
                data = data.filter(f => f.id != this.subscribedFeeIds[i]); 
              }          
            }

          // prepare data to display
          this.listData = new MatTableDataSource(data);      
          }, error => {
            console.log(error);
        });
      } 
}

Solution

You can implement either one of these methods:

1.) Enhance your @Input and @Output based on your code above:

stock-subscribe.component.ts

@Component({...})
export class StockSubscribeComponent implements OnInit {    

   @Output() subscribedFeeIds: EventEmitter<any> = new EventEmitter<any>(); 

   list: any[] = [];               // To store your ids, do not use the @Output variable above to push things inside a loop, you may not want to continuously emit data for an nth number of the sequence.

   ...

   createSubsList() {    

      ...
    
      for (var i = 0; i < data.length; i++) {
        ...
    
        if (data[i].status)
           this.list.push(data[i].fees[0].id);      // Push IDs on this.list not on this.subscribedFeeIds
      }  

      this.subscribedFeeIds.emit(this.list);        // After the loop finishes, emit the final list value
                                                    // Do not use .push() on @Output variable, this is an emission variable so use .emit()

   

   }

}

or you could also do any of these methods when handling your array list:

// METHOD #1
this.filteredIds = [];
for(const { status, fees } of FEES_DATA) {
   if (status) filteredIds.push(fees[0].id);
}

OR    

// METHOD #2
this.filteredIds = FEES_DATA
  .filter(({ status }) => status)
  .map(({ fees }) => fees[0].id);



// Then emit the filtered ids
this.list.emit(this.filteredIds);

stock-addsubs.component.ts

@Component({...})
export class StockAddsubsComponent implements OnInit {

   // Since you are waiting for emission from StockSubscribeComponent which the 
   // emission also waits till the loop is finished based on the code above, better to
   // implement the @Input like this so as to avoid processing a an empty list

   @Input() set subscribedFeeIds(list: any[]) {
       if (list && list.length) {              // If the list now has items, call createFeeList() function
         this.createFeeList();
       }
   } 

   ...

}

____

or

@Component({...})
export class StockAddsubsComponent implements OnInit, OnChanges {    // Add OnChanges

  @Input() subscribedFeeIds: any []; 


  ngOnChanges({ subscribedFeeIds }: SimpleChanges) {          // SimpleChanges from @angular/core

    if (subscribedFeeIds && subscribedFeeIds.currentValue && subscribedFeeIds.currentValue.length) {
      this.createFeeList();
    }

    // You can also console the subscribedFeeIds and check it's value or changes
    console.log(subscribedFeeIds);

  }

}

Have created a Stackblitz Demo for your reference


2.) Use RxJS Subject or BehaviorSubject to emit data

Use this Stackblitz Demo for your reference.



Answered By - KShewengger
Answer Checked By - David Marino (PHPFixing Volunteer)
Read More
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg

[FIXED] How to send output from component via router-outlet to parent component

 August 17, 2022     angular, components, javascript, output     No comments   

Issue

I need to emit a string when Parent page

<div class="container-fluid fluidy">
     <router-outlet (currentpage)="componentAdded($event)"></router-outlet>
</div>

Parentpage.ts

  componentAdded(stringer){
    console.log(stringer);
    this.currentpage = stringer;
  }

Child page

  @Output() currentpage = new EventEmitter<string>();

  ngOnInit(): void {
    this.currentpage.emit('profile');
  }

Solution

If a component is launching inside router-outlet, its no more a child component of component having router-outlet. hence normally having output on router-outlet tag will not work. Instead you can do something like

Parent component html

<router-outlet (activate)="componentActivated($event)" (deactivate)="componentDeactivated($event)"></router-outlet>

Parent component ts

componentAddedSubscription: Subscritption;
componentActivated(component) {
    if(component instanceof ChildComponent) {
         this.componentAddedSubscription = component.currentpage.subscribe(res=>{
              //your logic
         });   
    }
}

componentDeactivated(component) {
   if(component instanceof ChildComponent) {
         if(this.componentAddedSubscription?.unsubscribe) {
             this.componentAddedSubscription.unsubscribe();
         }
   }
}


Answered By - Aakash Garg
Answer Checked By - Pedro (PHPFixing Volunteer)
Read More
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg

Monday, August 1, 2022

[FIXED] How to change showTotal postiton in antd pagination component

 August 01, 2022     antd, components, pagination, reactjs     No comments   

Issue

showTotal is currently aligned to the left of the pagination ( list of numbers ) always.

How to change its position.

Refer to the image below to understand the expected behavior

enter image description here

Documentation for Reference: https://ant.design/components/pagination/


Solution

Altough it is a li inside a ul, you can trick it somehow using absolute position

.ant-pagination-total-text { 
  position: absolute;
  right: 0;
}

Example



Answered By - Apostolos
Answer Checked By - Marilyn (PHPFixing Volunteer)
Read More
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg

Wednesday, July 13, 2022

[FIXED] How can I toggle between 3 components in ReactJS

 July 13, 2022     components, javascript, react-component, reactjs, web-deployment     No comments   

Issue

I am having a hard time rendering components conditionally in React. I have successfully rendered 2 components (A and B) conditionally but couldn't find any successful way to add a third component (C) in our case

this is the code for 2 componnets:

function App() {
  const [click, setClick] = useState(true);

  const ShowA = () => setClick(true);
  const ShowB = () => setClick(false);

  return (
    <>
      <br />

      <button onClick={ShowA}>A </button>

      <button onClick={ShowB}>B </button>

      <div className="App">
        {click && <div> A </div>}

        {!click && <div>B</div>}
      </div>
    </>
  );
}

Is there any possible way I can add a third C component so I can toggle between them? I have been trying for 2 days but no success.

This is the link of Codesandbox if anyone's interested

https://codesandbox.io/s/musing-tesla-9gkpw?file=/src/index.js:100-481


Solution

You can put as many states as you want:

  function App() {
    const [displayA, setDisplayA] = useState(true);
    const [displayB, setDisplayB] = useState(true);
    const [displayC, setDisplayC] = useState(true);

    const showA = () => {
      setDisplayA(true);
      setDisplayB(false);
      setDisplayC(false);
    }
    const showB = () => {
      setDisplayA(false);
      setDisplayB(true);
      setDisplayC(false);
    };
    const showC = () => {
      setDisplayA(false);
      setDisplayB(false);
      setDisplayC(true);
    };

    return (
      <>
        <br />
  
        <button onClick={showA}>A</button>
        <button onClick={showB}>B</button>
        <button onClick={showC}>C</button>
  
        <div className="App">
          {displayA && <div>A</div>}
          {displayB && <div>B</div>}
          {displayC && <div>C</div>}
        </div>
      </>
    );
  }

And you can even put other things in your state, like JSX elements:

  function App() {
    const [elementToDisplay, setElementToDisplay] = useState("");

    const showA = () => {
      setElementToDisplay(<div>A</div>)
    }
    const showB = () => {
      setElementToDisplay(<div>B</div>)
    }
    const showC = () => {
      setElementToDisplay(<div>C</div>)
    }

    return (
      <>
        <br />
  
        <button onClick={showA}>A</button>
        <button onClick={showB}>B</button>
        <button onClick={showC}>C</button>
  
        <div className="App">
          {elementToDisplay}
        </div>
      </>
    );
  }


Answered By - Roman Mkrtchian
Answer Checked By - Willingham (PHPFixing Volunteer)
Read More
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg

[FIXED] How can I toggle between 3 components in ReactJS

 July 13, 2022     components, javascript, react-component, reactjs, web-deployment     No comments   

Issue

I am having a hard time rendering components conditionally in React. I have successfully rendered 2 components (A and B) conditionally but couldn't find any successful way to add a third component (C) in our case

this is the code for 2 componnets:

function App() {
  const [click, setClick] = useState(true);

  const ShowA = () => setClick(true);
  const ShowB = () => setClick(false);

  return (
    <>
      <br />

      <button onClick={ShowA}>A </button>

      <button onClick={ShowB}>B </button>

      <div className="App">
        {click && <div> A </div>}

        {!click && <div>B</div>}
      </div>
    </>
  );
}

Is there any possible way I can add a third C component so I can toggle between them? I have been trying for 2 days but no success.

This is the link of Codesandbox if anyone's interested

https://codesandbox.io/s/musing-tesla-9gkpw?file=/src/index.js:100-481


Solution

You can put as many states as you want:

  function App() {
    const [displayA, setDisplayA] = useState(true);
    const [displayB, setDisplayB] = useState(true);
    const [displayC, setDisplayC] = useState(true);

    const showA = () => {
      setDisplayA(true);
      setDisplayB(false);
      setDisplayC(false);
    }
    const showB = () => {
      setDisplayA(false);
      setDisplayB(true);
      setDisplayC(false);
    };
    const showC = () => {
      setDisplayA(false);
      setDisplayB(false);
      setDisplayC(true);
    };

    return (
      <>
        <br />
  
        <button onClick={showA}>A</button>
        <button onClick={showB}>B</button>
        <button onClick={showC}>C</button>
  
        <div className="App">
          {displayA && <div>A</div>}
          {displayB && <div>B</div>}
          {displayC && <div>C</div>}
        </div>
      </>
    );
  }

And you can even put other things in your state, like JSX elements:

  function App() {
    const [elementToDisplay, setElementToDisplay] = useState("");

    const showA = () => {
      setElementToDisplay(<div>A</div>)
    }
    const showB = () => {
      setElementToDisplay(<div>B</div>)
    }
    const showC = () => {
      setElementToDisplay(<div>C</div>)
    }

    return (
      <>
        <br />
  
        <button onClick={showA}>A</button>
        <button onClick={showB}>B</button>
        <button onClick={showC}>C</button>
  
        <div className="App">
          {elementToDisplay}
        </div>
      </>
    );
  }


Answered By - Roman Mkrtchian
Answer Checked By - Mildred Charles (PHPFixing Admin)
Read More
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg

Tuesday, April 19, 2022

[FIXED] Why Laravel component does not render correctly? Depends on the route?

 April 19, 2022     components, laravel, php     No comments   

Issue

When I hit http://127.0.0.1:8000/welcome everything renders fine. But with http://127.0.0.1:8000/hh/welcome the page looks like it has no CSS references or anything at all.

Any idea why it is like this and how to solve it? Thanks a lot!

routes > web.php

Route::get('/hh/welcome', [BikeController::class, 'show']);
Route::get('welcome', [BikeController::class, 'show']);

app > Http > Controllers > BikeController.php

    public function show(Bike $bike)
    {
        return view('bikes.show', [
            'bike' => $bike
        ]);
    }

resources > views > bikes > show.blade.php

<x-layout>
<h1>Hello World!</h1>
</x-layout>

resources > views > components > layout.blade.php

<!DOCTYPE html>
<html lang="de" dir="ltr">
  <head>
    <meta charset="utf-8" />
    <meta http-equiv="X-UA-Compatible" content="IE=edge" />
    <meta name="viewport" content="width=device-width, initial-scale=1" />

    <title>BM | Dashboard &amp; Web App Template</title>

    <link rel="apple-touch-icon" sizes="180x180" href="assets/img/favicons/apple-touch-icon.png" />
    <link rel="icon" type="image/png" sizes="32x32" href="assets/img/favicons/favicon-32x32.png" />
    <link rel="icon" type="image/png" sizes="16x16" href="assets/img/favicons/favicon-16x16.png" />
    <link rel="shortcut icon" type="image/x-icon" href="assets/img/favicons/favicon.ico" />
    <link rel="manifest" href="assets/img/favicons/manifest.json" />
    <meta name="msapplication-TileImage" content="assets/img/favicons/mstile-150x150.png" />
    <meta name="theme-color" content="#ffffff" />
    <script src="assets/js/config.js"></script>
    <script src="vendors/overlayscrollbars/OverlayScrollbars.min.js"></script>

    <link rel="preconnect" href="https://fonts.gstatic.com" />
    <link href="https://fonts.googleapis.com/css?family=Open+Sans:300,400,500,600,700%7cPoppins:300,400,500,600,700,800,900&amp;display=swap" rel="stylesheet" />
    <link href="vendors/overlayscrollbars/OverlayScrollbars.min.css" rel="stylesheet" />
    <link href="assets/css/theme-rtl.min.css" rel="stylesheet" id="style-rtl" />
    <link href="assets/css/theme.min.css" rel="stylesheet" id="style-default" />
    <link href="assets/css/user-rtl.min.css" rel="stylesheet" id="user-style-rtl" />
    <link href="assets/css/user.min.css" rel="stylesheet" id="user-style-default" />
    <script> 
        var isRTL = JSON.parse(localStorage.getItem("isRTL")); 
        if (isRTL) {   
            var linkDefault = document.getElementById("style-default");   
            var userLinkDefault = document.getElementById("user-style-default");   
            linkDefault.setAttribute("disabled", true);   
            userLinkDefault.setAttribute("disabled", true);   
            document.querySelector("html").setAttribute("dir", "rtl"); 
        } else {   
            var linkRTL = document.getElementById("style-rtl");   
            var userLinkRTL = document.getElementById("user-style-rtl");   
            linkRTL.setAttribute("disabled", true);   
            userLinkRTL.setAttribute("disabled", true); 
        }
    </script>
  </head>

  <body>
    <main class="main" id="top"> 
        <div class="container" data-layout="container">   
            <script>     
                var isFluid = JSON.parse(localStorage.getItem("isFluid"));     
                if (isFluid) {       
                    var container = document.querySelector("[data-layout]");       
                    container.classList.remove("container");       
                    container.classList.add("container-fluid");     
                }   
            </script>      
            @include('_nav-vertical')   
            <div class="content">     
                @include('_nav-top')
                {{ $slot }}
                @include('_footer')   
            </div>   
            {{-- @include('_modal')  --}}
        </div>
    </main>

    <script src="vendors/popper/popper.min.js"></script>
    <script src="vendors/bootstrap/bootstrap.min.js"></script>
    <script src="vendors/anchorjs/anchor.min.js"></script>
    <script src="vendors/is/is.min.js"></script>
    <script src="vendors/echarts/echarts.min.js"></script>
    <script src="vendors/fontawesome/all.min.js"></script>
    <script src="vendors/lodash/lodash.min.js"></script>
    <script src="https://polyfill.io/v3/polyfill.min.js?features=window.scroll"></script>
    <script src="vendors/list.js/list.min.js"></script>
    <script src="assets/js/theme.js"></script>
  </body>
</html>

Solution

Because you are currently loading your CSS relative to your URL

Try the following:

    <link href="{{asset('assets/css/example.css')}}" rel="stylesheet"/>

or take a look at: https://laravel.com/docs/9.x/helpers#method-asset



Answered By - Wouter Comello
Answer Checked By - Marilyn (PHPFixing Volunteer)
Read More
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg

Friday, January 21, 2022

[FIXED] merge attributes - how do I get them to function properly?

 January 21, 2022     components, laravel     No comments   

Issue

i have the following in a component stored in resources/views/components/green-button.blade.php in laravel 8.

<button {{ $attributes->merge(['type' => 'button', 'class' => 'px-4 inline-flex justify-center py-2 border border-transparent shadow-sm text-sm font-medium rounded-md text-white bg-green-600 hover:bg-green-700 focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-green-500']) }}>
    {{ $slot }}
</button>

I use it :

<x-green-button class="px-0"
                title="Click to show or hide data entry for {{$person->firstname}}."
                wire:click="toggleVisibility({{$person->id}})">
  <h3 class="my-1">{{$person->FullName_fh}}</h3>
</x-green-button>

The component has an x axis padding of px-4. I pass px-0, but there is no effect. What am I doing wrong?

rbd


Solution

You can use @props() to achieve the goal.

// In your component

@props(['customClass' => ''])

<button {{ $attributes->merge([
    'type'  => 'button', 
    'class' => 'all-your-classes ' . $customClass
]) }}>
    {{ $slot }}
</button>
// In your blade file

<x-green-button customClass="px-0">
    {{ $person->FullName_fh }}
</x-green-button>



Answered By - Samuel Ferdary
Read More
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg

Tuesday, January 18, 2022

[FIXED] OpenId Component: getting attributes back from Google using CakePHP

 January 18, 2022     cakephp, cakephp-2.0, components, openid     No comments   

Issue

Is there an example that I can use to successfully get OpenId user attributes (like name, email) back from Google using CakePHP and the OpenID component? When I try and add required parameters, I get a "The page you requested is invalid."

More detail

Component: http://code.42dh.com/openid/

If I don't request any "attributes", it works fine. As soon as I try and add a request for required / optional attributes as in the following example, I get an error from Google: "The page you requested is invalid."

Example (Not working for me): http://cakebaker.42dh.com/2008/02/12/using-the-openid-simple-registration-extension/

According to 1 source, the problem is:

The error was literally triggered by not including the openid.claimed_id and openid.identity parameters, which must be set to "http://specs.openid.net/auth/2.0/identifier_select". With these set, I get another error, which can be resolved by also filling out openid.realm, with the same value as openid.return_to.

Google OpenID: the page you requested is invalid

Code

function openidlogin() {

    $realm = 'http://' . $_SERVER['HTTP_HOST'];
    $returnTo = $realm . '/users/openidlogin';


    $url = "https://www.google.com/accounts/o8/id";
    if ($this->RequestHandler->isPost() && !$this->Openid->isOpenIDResponse()) {
        try {
            $this->Openid->authenticate($url, $returnTo, $realm); // WORKS !!!
            $this->Openid->authenticate($url, 'http://'.$_SERVER['SERVER_NAME'].'/users/login', 'http://'.$_SERVER['SERVER_NAME'], array('email'), array()); // FAILS
        } catch (InvalidArgumentException $e) {
            $this->Session->setFlash("Error: Invalid OpenId");
        } catch (Exception $error) {
            $this->Session->setFlash("Error: " + $error->getMessage());
        }
    } elseif ($this->Openid->isOpenIDResponse()) {

        $response = $this->Openid->getResponse($returnTo);

        if ($response->status == Auth_OpenID_CANCEL) {
            $this->Session->setFlash("Google Login Cancelled");
            $this->redirect(array("controller" => "users", "action" => "login"));
        } elseif ($response->status == Auth_OpenID_FAILURE) {
            $this->Session->setFlash("Veficiation Failed: " . $response->message);
            $this->redirect(array("controller" => "users", "action" => "login"));
        } elseif ($response->status == Auth_OpenID_SUCCESS) {

            $axResponse = Auth_OpenID_AX_FetchResponse::fromSuccessResponse($response);
            debug ($response);
            debug ($axResponse);
            $this->Session->setFlash("Authenticated");
        }
    }

Solution

Have a look at the following example: https://github.com/cakebaker/openid-component-example/blob/master/app/Controller/UsersController.php



Answered By - dhofstet
Read More
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg

Friday, December 31, 2021

[FIXED] Redirect to another controller with a Flash message - Cakephp 3

 December 31, 2021     cakephp, cakephp-3.0, components, exception, php     No comments   

Issue

There's a way to redirect from a component to a different controller (not the one who called the component) with a Flash message? Something like:

namespace App\Controller\Component;

use Cake\Controller\Component;

class ValidateValueComponent extends Component
{
    public function validateValue($var = null){
        try{
            if(!$var){
                throw new \Exception();
            }
        } catch(\Exception $e){
            $action = $this->request->params['action'] === 'index' ? 'home' : $this->request->params['action'];
            $controller = $action === 'home' ? 'Home' : $this->request->params['controller'];

            $this->_registry->getController()->Flash->error(__('Message!'));
            // $this->_registry->getController()->redirect(['controller' => $controller, 'action' => $action]);
        }
    }
}

I want to validate some values and avoid it to break the execution. If there are no value (not empty) on the $var I want to check if the error was called by the index method, if so send the user to the home page (HomeController) with the flash message. In the other case just send the user to the index from the controller who captured the error and show the flash message.

This code above allow me to show the Flash or redirect, but I cannot do both of them.

Anyway,

Thank you all!


Solution

Actually I solved using this link from bookstack.cn but overwall I needed to call the Flash component on my $components array and then use it normally, independant of the controller who has called the component. Something like:

namespace App\Controller\Component;

use Cake\Controller\Component;

class ValidateValueComponent extends Component
{
    public $components = ['Flash'];

    public function validateValue($var = null){
        try{
            if(!$var){
                throw new \Exception();
            }
        } catch(\Exception $e){
            $action = $this->request->params['action'] === 'index' ? 'home' : $this->request->params['action'];
            $controller = $action === 'home' ? 'Home' : $this->request->params['controller'];

            $this->Flash->set(__('Message!'));
            return $this->_registry->getController()->redirect(['controller' => $controller, 'action' => $action]);
        }
    }
}



Answered By - MarceloSnts
Read More
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg
Older Posts Home
View mobile version

Total Pageviews

Featured Post

Why Learn PHP Programming

Why Learn PHP Programming A widely-used open source scripting language PHP is one of the most popular programming languages in the world. It...

Subscribe To

Posts
Atom
Posts
All Comments
Atom
All Comments

Copyright © PHPFixing