Foreach loop only working on last item - comments

What I'm trying to do is find the URL's in comments and then check those URL's against an array. If the URL is in the array and has the key 'data' with a certain value then I want to replace each URL in the comment with custom text.
I have everything working except the replacing part. This is what I have so far.
the comment
Lorem www.link1.com and ipsum dolor sit amet, http://link2.com consectetur
adipiscing elit. Maecenas http://link3.com eu tempor nibh.
The array the function is using
Array
(
[0] => Array
(
[status] => 200
[data] => one
[url] => www.link1.com
)
[1] => Array
(
[status] => 204
[data] =>
[url] => http://link2.com
)
[2] => Array
(
[status] => 200
[data] => two
[url] => http://link3.com
)
)
the function
function check_the_status( $arrays, $comment ) {
// Bad statis types
$status = apply_filters( 'status_filter', array( 'one', 'two', 'three' ) );
$modified = '';
foreach( $arrays as $key => $array ){
$url = $array['url'];
$data = $array['data'];
if( in_array( $data, $status ) ) {
$modified = '<span>the new text</span>';
$the_comment = str_replace( $url, $modified, $comment );
}
}
return $the_comment;
}
the output
Lorem www.link1.com and ipsum dolor sit amet, http://link2.com consectetur
adipiscing elit. Maecenas "<span>the new text</span>" eu tempor nibh.
So, what's happening with this function, is it's only applying the new text to the last URL in the array, but I want it to be applied to the first and last URL's because they both have the data value I'm checking for in the array. I'm thinking the foreach loop isn't the right way to achieve what I want, but I'm not sure what's the best way.

The problem appears to be with the following line. You are starting over with each iteration by passing $comment each time:
$the_comment = str_replace( $url, $modified, $comment );
You should change it to:
$the_comment = str_replace( $url, $modified, $the_comment );
and intialize $the_comment before the loop:
$the_comment = $comment;
Based on additional comments, here's the working code. I added "bold" style so the result is more pronounced.
$arrays = Array
(
0 => Array
(
'status' => 200,
'data' => 'one',
'url' => 'www.link1.com'
),
1 => Array
(
'status' => 204,
'data' => '',
'url' => 'http://link2.com'
),
2 => Array
(
'status' => 200,
'data' => 'two',
'url' => 'http://link3.com'
)
);
function check_the_status( $arrays, $comment ) {
// Bad statis types
$status = apply_filters( 'status_filter', array( 'one', 'two', 'three' ) );
// The class for targeting the url
$span_class = apply_filters( 'status_class', 'sl-unsafe-link' );
$modified = '';
$the_comment = $comment;
foreach( $arrays as $key => $array ){
$url = $array['url'];
$data = $array['data'];
if( in_array( $data, $status ) ) {
$modified = '<span style="font-weight:bold">'.$url.'</span>';
$the_comment = str_replace( $url, $modified, $the_comment );
}
}
return $the_comment;
}
$comment = 'Lorem www.link1.com and ipsum dolor sit amet, http://link2.com consectetur adipiscing elit. Maecenas http://link3.com eu tempor nibh.';
$new = check_the_status($arrays, $comment);
echo $new;
I ran it locally and this is the output:
Lorem <span style="font-weight:bold">www.link1.com</span> and ipsum dolor sit amet, http://link2.com consectetur adipiscing elit. Maecenas <span style="font-weight:bold">http://link3.com</span> eu tempor nibh.

Related

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'];
}

Laravel collection variable null return

I have a DB table name is the product. when I query (eloquent) to that table return collection object with all the fields. but I access the banner_image field every time return a null value.
but I can access the other variables in that collection working fine.
If I Defining An Accessor, the issue is solved. I want to know about, whats the issue only for one variable.
DD to eloquent collection
#original: array:20 [▼
"id" => 2
"type_id" => 2
"banking_id" => 1
"page" => "savings-accounts"
"url_slug" => "repellat-corporis-id-distinctio"
"title" => "{"en":"Mertz Underpass","si":"","ta":""}"
"short_description" => "{"en":"Ut laboriosam expedita qui repellat labore ut qui suscipit blanditiis fuga fugit et rerum.","si":"","ta":""}"
"interest_rate" => 40.9
"first_link_text" => null
"second_link_text" => null
"image" => "https://dummyimage.com/716x500"
"banner_image" => "https://dummyimage.com/716x500"
"banner_description" => "{"en":"Est placeat et aut laborum consequatur ab quas esse totam voluptatem et atque adipisci est quaerat aut et.","si":"","ta":""}"
"landing_page" => 0
"side_block" => null
"calculator" => null
"sort" => 0
"created_at" => null
"updated_at" => null
"deleted_at" => null
]
when I access the $innerProduct->banner_image (in controller) every time return null value.
I have found the issue. accidentally Ill added that column to translation array.
public $translatable = [
'title', 'short_description', 'first_link_text', 'second_link_text', 'banner_description','banner_image'
];

Laravel: how do I pass obj std class to my view and call it and the difference with passing a simple array?

I would like to ask on how will I display this type of array in laravel blade view?
Array(
[0] => stdClass Object
(
[id] => 2
[email] => email#email.com
[username] => dodie
[firstname] => Jhon
[lastname] => David
[password] => $2y$08$x12gVo54SsUW0U1aHTHaXu7VbgHFG8So9.fd/DfczT7KOyk4J1nLS
[location] => {'long':47.061469, 'lat': 8.321743}
[photo] => 1.jpg
[hometown] => England
[Updated] => 1
[description] => "Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum."
[role] => client
[deleted_at] =>
[created_at] => 2013-10-10 06:00:18
[updated_at] => 2013-10-10 07:24:22
[reviewer_id] => 1
[company_id] => 2
[title] => Very Bad Ass
[content] => badass
[review_rating] => 1
[helpful] => 0
[logo] => 2.jpg
[contactperson] => Jhon Doe
[companyname] => Hardy Contractor
[address] => makati Philippines
[type] => Heating and Airconditioning
[stars] => 2
[phone] => 554-9266
[fax] => Hardy Contractor
[website] => www.hardycontractors.com
)
This is how I pass this In my Controller:
$data = DB::select($query); //fetching data using Query Builder
return View::make('home')->with('users', $data);
this is how I call it on my blade view:
$users->website
Every time I call this on my blade
can you please enlighten me? :) I want to understand more on how I can handle this kind of problem.
What you have is an array of std class object.
In your view you can simply loop through them:
#foreach($users as $user)
{{ $user->website }}
#endforeach
In case you have one and only one object in the array, you might want to consider passing $users[0] to the view and then work with it as a single object.

CakePHP: Validation message not showing but $this->validationErrors works

I have a field gentel_id with the following validation rules in my model Contrat:
public $validate = array(
'gentel_id' => array(
'numeric' => array(
'rule' => 'numeric',
'required' => true,
'allowEmpty' => false,
'message' => 'Veuillez entrer un identifiant GENTEL ou mettre la valeur 0000000000',
),
),
);
In my controller:
public function add($id = null) {
if ($this->request->is('post')) {
$this->Contrat->create();
if ($this->Contrat->save($this->request->data)) {
$this->Session->setFlash(__('Le Contrat a été ajouté'));
$this->redirect(array('action' => 'edit', $this->Contrat->getInsertID() ));
} else {
debug($this->Contrat->validationErrors);
$this->Session->setFlash(__('Le Contrat ne peut être ajouté'));
}
$this->set('id',$id);
...
}
In my form:
<?php echo $this->Form->create('Contrat');?>
<?php
if (empty($id)){
echo $this->Form->input('client_id',array('empty' => "Client non défini",'default' => $id, 'onchange'=>"window.location.href= '/contrats/add/'+this.form.ContratClientId.options[this.form.ContratClientId.selectedIndex].value"));
}else{
echo "<span class=\"label\">".__('Client')."</span>".$this->Kaldom->link(h($clients[$id]),array('controller' => 'clients', 'action' => 'view',$id));
echo $this->Form->input('client_id', array('type' => 'hidden','value' => $id));
}
echo $this->Form->input('gentel_id',array('type'=>'text','label'=> 'Gentel ID'));
?>
<?php echo $this->Form->end(__('Créer'));?>
When I try to save my form with "gentel_id" empty, the save is correctly not done and a debug ($this->Contrat->validationErrors) give me this:
Array
(
[gentel_id] => Array
(
[0] => Veuillez entrer un identifiant GENTEL ou mettre la valeur 0000000000
)
)
But the error messsage is not displayed in my form.
Note that it is an add function but I have passed a parameter in the url like this:
.../contrats/add/3
Can you help me please?

Saving the output from a ruby script into my rails database

I wrote a small ruby script that generates an array like the one below:
{:title=>"Lorem ipsum",
:category=>["Lorem ipsum"],
:items=>
["Lorem ipsum",
"Lorem ipsum",
"Lorem ipsum"],
:process=>
["Sed ut perspiciatis unde omnis iste natus error."]}
How can I run that script in order to save the output into my rails database?
With a bit of guessing... you can write this is a rake task:
WeDontKnowWhichModelHere.create!({
:title => "Lorem ipsum",
:categories => [Category.new(:name => "Lorem ipsum"), ...],
:items => [Item.new(:name => "Lorem ipsum"), ...],
:processes => [Process.new(:name => "Sed ut perspiciatis unde omnis iste natus error")],
})

Resources